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