example_test.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. // Copyright (c) 2015-2019 Jeevanandam M. (jeeva@myjeeva.com), All rights reserved.
  2. // resty source code and usage is governed by a MIT style
  3. // license that can be found in the LICENSE file.
  4. package resty_test
  5. import (
  6. "crypto/tls"
  7. "fmt"
  8. "io/ioutil"
  9. "log"
  10. "net/http"
  11. "os"
  12. "strconv"
  13. "time"
  14. "golang.org/x/net/proxy"
  15. "gopkg.in/resty.v1"
  16. )
  17. type DropboxError struct {
  18. Error string
  19. }
  20. type AuthSuccess struct {
  21. /* variables */
  22. }
  23. type AuthError struct {
  24. /* variables */
  25. }
  26. type Article struct {
  27. Title string
  28. Content string
  29. Author string
  30. Tags []string
  31. }
  32. type Error struct {
  33. /* variables */
  34. }
  35. //
  36. // Package Level examples
  37. //
  38. func Example_get() {
  39. resp, err := resty.R().Get("http://httpbin.org/get")
  40. fmt.Printf("\nError: %v", err)
  41. fmt.Printf("\nResponse Status Code: %v", resp.StatusCode())
  42. fmt.Printf("\nResponse Status: %v", resp.Status())
  43. fmt.Printf("\nResponse Body: %v", resp)
  44. fmt.Printf("\nResponse Time: %v", resp.Time())
  45. fmt.Printf("\nResponse Received At: %v", resp.ReceivedAt())
  46. }
  47. func Example_enhancedGet() {
  48. resp, err := resty.R().
  49. SetQueryParams(map[string]string{
  50. "page_no": "1",
  51. "limit": "20",
  52. "sort": "name",
  53. "order": "asc",
  54. "random": strconv.FormatInt(time.Now().Unix(), 10),
  55. }).
  56. SetHeader("Accept", "application/json").
  57. SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F").
  58. Get("/search_result")
  59. printOutput(resp, err)
  60. }
  61. func Example_post() {
  62. // POST JSON string
  63. // No need to set content type, if you have client level setting
  64. resp, err := resty.R().
  65. SetHeader("Content-Type", "application/json").
  66. SetBody(`{"username":"testuser", "password":"testpass"}`).
  67. SetResult(AuthSuccess{}). // or SetResult(&AuthSuccess{}).
  68. Post("https://myapp.com/login")
  69. printOutput(resp, err)
  70. // POST []byte array
  71. // No need to set content type, if you have client level setting
  72. resp1, err1 := resty.R().
  73. SetHeader("Content-Type", "application/json").
  74. SetBody([]byte(`{"username":"testuser", "password":"testpass"}`)).
  75. SetResult(AuthSuccess{}). // or SetResult(&AuthSuccess{}).
  76. Post("https://myapp.com/login")
  77. printOutput(resp1, err1)
  78. // POST Struct, default is JSON content type. No need to set one
  79. resp2, err2 := resty.R().
  80. SetBody(resty.User{Username: "testuser", Password: "testpass"}).
  81. SetResult(&AuthSuccess{}). // or SetResult(AuthSuccess{}).
  82. SetError(&AuthError{}). // or SetError(AuthError{}).
  83. Post("https://myapp.com/login")
  84. printOutput(resp2, err2)
  85. // POST Map, default is JSON content type. No need to set one
  86. resp3, err3 := resty.R().
  87. SetBody(map[string]interface{}{"username": "testuser", "password": "testpass"}).
  88. SetResult(&AuthSuccess{}). // or SetResult(AuthSuccess{}).
  89. SetError(&AuthError{}). // or SetError(AuthError{}).
  90. Post("https://myapp.com/login")
  91. printOutput(resp3, err3)
  92. }
  93. func Example_dropboxUpload() {
  94. // For example: upload file to Dropbox
  95. // POST of raw bytes for file upload.
  96. file, _ := os.Open("/Users/jeeva/mydocument.pdf")
  97. fileBytes, _ := ioutil.ReadAll(file)
  98. // See we are not setting content-type header, since go-resty automatically detects Content-Type for you
  99. resp, err := resty.R().
  100. SetBody(fileBytes). // resty autodetects content type
  101. SetContentLength(true). // Dropbox expects this value
  102. SetAuthToken("<your-auth-token>").
  103. SetError(DropboxError{}).
  104. Post("https://content.dropboxapi.com/1/files_put/auto/resty/mydocument.pdf") // you can use PUT method too dropbox supports it
  105. // Output print
  106. fmt.Printf("\nError: %v\n", err)
  107. fmt.Printf("Time: %v\n", resp.Time())
  108. fmt.Printf("Body: %v\n", resp)
  109. }
  110. func Example_put() {
  111. // Just one sample of PUT, refer POST for more combination
  112. // request goes as JSON content type
  113. // No need to set auth token, error, if you have client level settings
  114. resp, err := resty.R().
  115. SetBody(Article{
  116. Title: "go-resty",
  117. Content: "This is my article content, oh ya!",
  118. Author: "Jeevanandam M",
  119. Tags: []string{"article", "sample", "resty"},
  120. }).
  121. SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD").
  122. SetError(&Error{}). // or SetError(Error{}).
  123. Put("https://myapp.com/article/1234")
  124. printOutput(resp, err)
  125. }
  126. func Example_clientCertificates() {
  127. // Parsing public/private key pair from a pair of files. The files must contain PEM encoded data.
  128. cert, err := tls.LoadX509KeyPair("certs/client.pem", "certs/client.key")
  129. if err != nil {
  130. log.Fatalf("ERROR client certificate: %s", err)
  131. }
  132. resty.SetCertificates(cert)
  133. }
  134. func Example_customRootCertificate() {
  135. resty.SetRootCertificate("/path/to/root/pemFile.pem")
  136. }
  137. //
  138. // top level method examples
  139. //
  140. func ExampleNew() {
  141. // Creating client1
  142. client1 := resty.New()
  143. resp1, err1 := client1.R().Get("http://httpbin.org/get")
  144. fmt.Println(resp1, err1)
  145. // Creating client2
  146. client2 := resty.New()
  147. resp2, err2 := client2.R().Get("http://httpbin.org/get")
  148. fmt.Println(resp2, err2)
  149. }
  150. //
  151. // Client object methods
  152. //
  153. func ExampleClient_SetCertificates() {
  154. // Parsing public/private key pair from a pair of files. The files must contain PEM encoded data.
  155. cert, err := tls.LoadX509KeyPair("certs/client.pem", "certs/client.key")
  156. if err != nil {
  157. log.Fatalf("ERROR client certificate: %s", err)
  158. }
  159. resty.SetCertificates(cert)
  160. }
  161. //
  162. // Resty Socks5 Proxy request
  163. //
  164. func Example_socks5Proxy() {
  165. // create a dialer
  166. dialer, err := proxy.SOCKS5("tcp", "127.0.0.1:9150", nil, proxy.Direct)
  167. if err != nil {
  168. log.Fatalf("Unable to obtain proxy dialer: %v\n", err)
  169. }
  170. // create a transport
  171. ptransport := &http.Transport{Dial: dialer.Dial}
  172. // set transport into resty
  173. resty.SetTransport(ptransport)
  174. resp, err := resty.R().Get("http://check.torproject.org")
  175. fmt.Println(err, resp)
  176. }
  177. func printOutput(resp *resty.Response, err error) {
  178. fmt.Println(resp, err)
  179. }