github.com/subosito/twilio@v0.0.1/twilio.go (about) 1 package twilio 2 3 import ( 4 "fmt" 5 "io/ioutil" 6 "net/http" 7 "net/url" 8 "strings" 9 ) 10 11 const ( 12 apiHost = "https://api.twilio.com" 13 apiVersion = "2010-04-01" 14 apiFormat = "json" 15 ) 16 17 type Twilio struct { 18 AccountSid string 19 AuthToken string 20 BaseUrl string 21 22 // Transport is the HTTP transport to use when making requests. 23 // It will default to http.DefaultTransport if nil 24 Transport http.RoundTripper 25 } 26 27 func NewTwilio(accountSid, authToken string) *Twilio { 28 baseUrl := fmt.Sprintf("%s/%s", apiHost, apiVersion) 29 return &Twilio{accountSid, authToken, baseUrl, nil} 30 } 31 32 func (t *Twilio) transport() http.RoundTripper { 33 if t.Transport != nil { 34 return t.Transport 35 } 36 37 return http.DefaultTransport 38 } 39 40 func (t *Twilio) request(method string, u string, v url.Values) (b []byte, status int, err error) { 41 // remove empty value 42 for key, val := range v { 43 if strings.Join(val, "") == "" { 44 v.Del(key) 45 } 46 } 47 48 req, err := http.NewRequest(method, u, strings.NewReader(v.Encode())) 49 if err != nil { 50 return nil, 0, err 51 } 52 53 if method == "POST" { 54 req.Header.Add("Content-Type", "application/x-www-form-urlencoded") 55 } 56 57 req.SetBasicAuth(t.AccountSid, t.AuthToken) 58 req.Header.Set("Accept", "application/json") 59 req.Header.Set("Accept-Charset", "utf-8") 60 61 client := &http.Client{Transport: t.transport()} 62 63 res, err := client.Do(req) 64 if err != nil { 65 return nil, res.StatusCode, err 66 } 67 defer res.Body.Close() 68 69 b, err = ioutil.ReadAll(res.Body) 70 if err == nil { 71 return b, res.StatusCode, nil 72 } 73 74 return nil, res.StatusCode, err 75 }