Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package client
- import (
- "bytes"
- "code.google.com/p/gorilla/rpc"
- "code.google.com/p/gorilla/rpc/json"
- "io"
- "net/http"
- )
- type Codec interface {
- ContentType() string
- EncodeRequest(method string, args interface{}) ([]byte, error)
- DecodeResponse(r io.Reader, reply interface{}) error
- }
- type jsonCodec struct{}
- func (jsonCodec) EncodeRequest(method string, args interface{}) ([]byte, error) {
- return json.EncodeClientRequest(method, args)
- }
- func (jsonCodec) DecodeResponse(r io.Reader, reply interface{}) error {
- return json.DecodeClientResponse(r, reply)
- }
- func (jsonCodec) ContentType() string {
- return "application/json"
- }
- var JsonCodec Codec = jsonCodec{}
- type Client struct {
- path string
- codec Codec
- client *http.Client
- }
- func NewClient(path string, client *http.Client, codec Codec) *Client {
- return &Client{
- path: path,
- codec: codec,
- client: client,
- }
- }
- func (c *Client) Call(method string, args interface{}, reply interface{}) (err error) {
- buf, err := c.codec.EncodeRequest(method, args)
- if err != nil {
- return
- }
- body := bytes.NewReader(buf)
- req, err := http.NewRequest("POST", c.path, body)
- if err != nil {
- return
- }
- req.Header.Set("Content-Type", c.codec.ContentType())
- resp, err := c.client.Do(req)
- if err != nil {
- return
- }
- defer resp.Body.Close()
- err = c.codec.DecodeResponse(resp.Body, reply)
- return
- }
Add Comment
Please, Sign In to add comment