Guest User

Untitled

a guest
Nov 21st, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. package client
  2.  
  3. import (
  4. "bytes"
  5. "code.google.com/p/gorilla/rpc"
  6. "code.google.com/p/gorilla/rpc/json"
  7. "io"
  8. "net/http"
  9. )
  10.  
  11. type Codec interface {
  12. ContentType() string
  13. EncodeRequest(method string, args interface{}) ([]byte, error)
  14. DecodeResponse(r io.Reader, reply interface{}) error
  15. }
  16.  
  17. type jsonCodec struct{}
  18.  
  19. func (jsonCodec) EncodeRequest(method string, args interface{}) ([]byte, error) {
  20. return json.EncodeClientRequest(method, args)
  21. }
  22.  
  23. func (jsonCodec) DecodeResponse(r io.Reader, reply interface{}) error {
  24. return json.DecodeClientResponse(r, reply)
  25. }
  26.  
  27. func (jsonCodec) ContentType() string {
  28. return "application/json"
  29. }
  30.  
  31. var JsonCodec Codec = jsonCodec{}
  32.  
  33. type Client struct {
  34. path string
  35. codec Codec
  36. client *http.Client
  37. }
  38.  
  39. func NewClient(path string, client *http.Client, codec Codec) *Client {
  40. return &Client{
  41. path: path,
  42. codec: codec,
  43. client: client,
  44. }
  45. }
  46.  
  47. func (c *Client) Call(method string, args interface{}, reply interface{}) (err error) {
  48. buf, err := c.codec.EncodeRequest(method, args)
  49. if err != nil {
  50. return
  51. }
  52. body := bytes.NewReader(buf)
  53. req, err := http.NewRequest("POST", c.path, body)
  54. if err != nil {
  55. return
  56. }
  57. req.Header.Set("Content-Type", c.codec.ContentType())
  58.  
  59. resp, err := c.client.Do(req)
  60. if err != nil {
  61. return
  62. }
  63. defer resp.Body.Close()
  64.  
  65. err = c.codec.DecodeResponse(resp.Body, reply)
  66. return
  67. }
Add Comment
Please, Sign In to add comment