Created
August 5, 2013 12:00
-
-
Save kolo/6155412 to your computer and use it in GitHub Desktop.
Example of proxy for using JSON-RPC in Go via HTTP.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"bytes" | |
"fmt" | |
"log" | |
"net/http" | |
"net/rpc/jsonrpc" | |
) | |
type proxy struct { | |
url string | |
httpClient *http.Client | |
cookies []*http.Cookie | |
request *http.Request | |
} | |
func (p *proxy) Read(b []byte) (int, error) { | |
resp, err := p.httpClient.Do(p.request) | |
if err != nil { | |
return 0, err | |
} | |
if p.cookies == nil { | |
p.cookies = resp.Cookies() | |
} | |
r := bufio.NewReader(resp.Body) | |
n, err := r.Read(b) | |
if err != nil { | |
return 0, nil | |
} | |
resp.Body.Close() | |
return n, nil | |
} | |
func (p *proxy) Write(b []byte) (int, error) { | |
req, err := http.NewRequest("POST", p.url, bytes.NewReader(b)) | |
if err != nil { | |
return 0, err | |
} | |
n := len(b) | |
req.Header.Set("Content-Type", "application/json") | |
req.Header.Set("Content-Length", fmt.Sprintf("%d", n)) | |
if p.cookies != nil { | |
for _, cookie := range p.cookies { | |
req.AddCookie(cookie) | |
} | |
} | |
p.request = req | |
return n, nil | |
} | |
func (p *proxy) Close() error { | |
return nil | |
} | |
func newProxy(url string, transport *http.Transport) *proxy { | |
if transport == nil { | |
transport = &http.Transport{} | |
} | |
httpClient := &http.Client{Transport: transport} | |
return &proxy{ | |
url: url, | |
httpClient: httpClient, | |
} | |
} | |
func main() { | |
proxy := newProxy("https://bugzilla.mozilla.org/jsonrpc.cgi", nil) | |
client := jsonrpc.NewClient(proxy) | |
result := map[string]interface{}{} | |
err := client.Call("Bugzilla.version", nil, &result) | |
if err != nil { | |
log.Printf("Error: %s\n", err.Error()) | |
return | |
} | |
log.Printf("Version = %v\n", result["version"]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There is a problem, proxy#Read called twice, presumably by Decode method of json.Decoder, but I'm not sure.