Advertisement
Guest User

Untitled

a guest
May 23rd, 2015
287
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.07 KB | None | 0 0
  1. package jsonclient
  2.  
  3. import (
  4.     "bytes"
  5.     "net"
  6.     "time"
  7.     "io/ioutil"
  8.     "net/http"
  9. )
  10.  
  11. type Config struct {
  12.     Url    string
  13.     Data   []byte
  14.     Method string
  15. }
  16.  
  17. type Client struct {
  18.     Config     *Config
  19.     HttpClient *http.Client
  20. }
  21.  
  22. func NewClient(c *Config) (*Client, error) {
  23.     s := new(Client)
  24.  
  25.     // HTTP client
  26.     s.Config = c
  27.     s.HttpClient = &http.Client{
  28.         Transport: &http.Transport{
  29.             Dial: func(network, addr string) (net.Conn, error) {
  30.                 return net.DialTimeout(network, addr, time.Duration(time.Second*3))
  31.             },
  32.         },
  33.     }
  34.  
  35.     return s, nil
  36.  
  37. }
  38.  
  39. func Dial(c *Client) string {
  40.  
  41.     req, err := http.NewRequest(c.Config.Method, c.Config.Url, bytes.NewBuffer(c.Config.Data))
  42.     req.Header.Set("Content-Type", "application/json")
  43.     req.Header.Set("Accept", "application/json")
  44.  
  45.     client := &http.Client{}
  46.     resp, err := client.Do(req)
  47.     if err != nil {
  48.         panic(err)
  49.     }
  50.     defer resp.Body.Close()
  51.  
  52.     //fmt.Println("response Status:", resp.Status)
  53.     //fmt.Println("response Headers:", resp.Header)
  54.     body, _ := ioutil.ReadAll(resp.Body)
  55.  
  56.     return string(body)
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement