1<p align="center"> 2<h1 align="center">Resty</h1> 3<p align="center">Simple HTTP and REST client library for Go (inspired by Ruby rest-client)</p> 4<p align="center"><a href="#features">Features</a> section describes in detail about Resty capabilities</p> 5</p> 6<p align="center"> 7<p align="center"><a href="https://travis-ci.org/go-resty/resty"><img src="https://travis-ci.org/go-resty/resty.svg?branch=master" alt="Build Status"></a> <a href="https://codecov.io/gh/go-resty/resty/branch/master"><img src="https://codecov.io/gh/go-resty/resty/branch/master/graph/badge.svg" alt="Code Coverage"></a> <a href="https://goreportcard.com/report/go-resty/resty"><img src="https://goreportcard.com/badge/go-resty/resty" alt="Go Report Card"></a> <a href="https://github.com/go-resty/resty/releases/latest"><img src="https://img.shields.io/badge/version-1.9.1-blue.svg" alt="Release Version"></a> <a href="https://godoc.org/github.com/go-resty/resty"><img src="https://godoc.org/github.com/go-resty/resty?status.svg" alt="GoDoc"></a> <a href="LICENSE"><img src="https://img.shields.io/github/license/go-resty/resty.svg" alt="License"></a></p> 8</p> 9 10## News 11 12 * [Collecting Inputs for Resty v2.0.0](https://github.com/go-resty/resty/issues/166) 13 * v1.9.1 [released](https://github.com/go-resty/resty/releases/latest) and tagged on Aug 29, 2018. 14 * v1.0 released - Resty's first version was released on Sep 15, 2015 then it grew gradually as a very handy and helpful library. Its been a two years; `v1.0` was released on Sep 25, 2017. I'm very thankful to Resty users and its [contributors](https://github.com/go-resty/resty/graphs/contributors). 15 16## Features 17 18 * GET, POST, PUT, DELETE, HEAD, PATCH, OPTIONS, etc. 19 * Simple and chainable methods for settings and request 20 * Request Body can be `string`, `[]byte`, `struct`, `map`, `slice` and `io.Reader` too 21 * Auto detects `Content-Type` 22 * Buffer less processing for `io.Reader` 23 * [Response](https://godoc.org/github.com/go-resty/resty#Response) object gives you more possibility 24 * Access as `[]byte` array - `response.Body()` OR Access as `string` - `response.String()` 25 * Know your `response.Time()` and when we `response.ReceivedAt()` 26 * Automatic marshal and unmarshal for `JSON` and `XML` content type 27 * Default is `JSON`, if you supply `struct/map` without header `Content-Type` 28 * For auto-unmarshal, refer to - 29 - Success scenario [Request.SetResult()](https://godoc.org/github.com/go-resty/resty#Request.SetResult) and [Response.Result()](https://godoc.org/github.com/go-resty/resty#Response.Result). 30 - Error scenario [Request.SetError()](https://godoc.org/github.com/go-resty/resty#Request.SetError) and [Response.Error()](https://godoc.org/github.com/go-resty/resty#Response.Error). 31 - Supports [RFC7807](https://tools.ietf.org/html/rfc7807) - `application/problem+json` & `application/problem+xml` 32 * Easy to upload one or more file(s) via `multipart/form-data` 33 * Auto detects file content type 34 * Request URL [Path Params (aka URI Params)](https://godoc.org/github.com/go-resty/resty#Request.SetPathParams) 35 * Backoff Retry Mechanism with retry condition function [reference](retry_test.go) 36 * resty client HTTP & REST [Request](https://godoc.org/github.com/go-resty/resty#Client.OnBeforeRequest) and [Response](https://godoc.org/github.com/go-resty/resty#Client.OnAfterResponse) middlewares 37 * `Request.SetContext` supported `go1.7` and above 38 * Authorization option of `BasicAuth` and `Bearer` token 39 * Set request `ContentLength` value for all request or particular request 40 * Choose between HTTP and REST mode. Default is `REST` 41 * `HTTP` - default up to 10 redirects and no automatic response unmarshal 42 * `REST` - defaults to no redirects and automatic response marshal/unmarshal for `JSON` & `XML` 43 * Custom [Root Certificates](https://godoc.org/github.com/go-resty/resty#Client.SetRootCertificate) and Client [Certificates](https://godoc.org/github.com/go-resty/resty#Client.SetCertificates) 44 * Download/Save HTTP response directly into File, like `curl -o` flag. See [SetOutputDirectory](https://godoc.org/github.com/go-resty/resty#Client.SetOutputDirectory) & [SetOutput](https://godoc.org/github.com/go-resty/resty#Request.SetOutput). 45 * Cookies for your request and CookieJar support 46 * SRV Record based request instead of Host URL 47 * Client settings like `Timeout`, `RedirectPolicy`, `Proxy`, `TLSClientConfig`, `Transport`, etc. 48 * Optionally allows GET request with payload, see [SetAllowGetMethodPayload](https://godoc.org/github.com/go-resty/resty#Client.SetAllowGetMethodPayload) 49 * Supports registering external JSON library into resty, see [how to use](https://github.com/go-resty/resty/issues/76#issuecomment-314015250) 50 * Exposes Response reader without reading response (no auto-unmarshaling) if need be, see [how to use](https://github.com/go-resty/resty/issues/87#issuecomment-322100604) 51 * Option to specify expected `Content-Type` when response `Content-Type` header missing. Refer to [#92](https://github.com/go-resty/resty/issues/92) 52 * Resty design 53 * Have client level settings & options and also override at Request level if you want to 54 * Request and Response middlewares 55 * Create Multiple clients if you want to `resty.New()` 56 * Supports `http.RoundTripper` implementation, see [SetTransport](https://godoc.org/github.com/go-resty/resty#Client.SetTransport) 57 * goroutine concurrent safe 58 * REST and HTTP modes 59 * Debug mode - clean and informative logging presentation 60 * Gzip - Go does it automatically also resty has fallback handling too 61 * Works fine with `HTTP/2` and `HTTP/1.1` 62 * [Bazel support](#bazel-support) 63 * Easily mock resty for testing, [for e.g.](#mocking-http-requests-using-httpmock-library) 64 * Well tested client library 65 66Resty works with `go1.3` and above. 67 68### Included Batteries 69 70 * Redirect Policies - see [how to use](#redirect-policy) 71 * NoRedirectPolicy 72 * FlexibleRedirectPolicy 73 * DomainCheckRedirectPolicy 74 * etc. [more info](redirect.go) 75 * Retry Mechanism [how to use](#retries) 76 * Backoff Retry 77 * Conditional Retry 78 * SRV Record based request instead of Host URL [how to use](resty_test.go#L1412) 79 * etc (upcoming - throw your idea's [here](https://github.com/go-resty/resty/issues)). 80 81## Installation 82 83#### Stable Version - Production Ready 84 85Please refer section [Versioning](#versioning) for detailed info. 86 87##### go.mod 88 89```bash 90require gopkg.in/resty.v1 v1.9.1 91``` 92 93##### go get 94```bash 95go get -u gopkg.in/resty.v1 96``` 97 98#### Latest Version - Development Edge 99 100```bash 101# install the latest & greatest library 102go get -u github.com/go-resty/resty 103``` 104 105## It might be beneficial for your project :smile: 106 107Resty author also published following projects for Go Community. 108 109 * [aah framework](https://aahframework.org) - A secure, flexible, rapid Go web framework. 110 * [go-model](https://github.com/jeevatkm/go-model) - Robust & Easy to use model mapper and utility methods for Go `struct`. 111 112## Usage 113 114The following samples will assist you to become as comfortable as possible with resty library. Resty comes with ready to use DefaultClient. 115 116Import resty into your code and refer it as `resty`. 117 118```go 119import "gopkg.in/resty.v1" 120``` 121 122#### Simple GET 123 124```go 125// GET request 126resp, err := resty.R().Get("http://httpbin.org/get") 127 128// explore response object 129fmt.Printf("\nError: %v", err) 130fmt.Printf("\nResponse Status Code: %v", resp.StatusCode()) 131fmt.Printf("\nResponse Status: %v", resp.Status()) 132fmt.Printf("\nResponse Time: %v", resp.Time()) 133fmt.Printf("\nResponse Received At: %v", resp.ReceivedAt()) 134fmt.Printf("\nResponse Body: %v", resp) // or resp.String() or string(resp.Body()) 135// more... 136 137/* Output 138Error: <nil> 139Response Status Code: 200 140Response Status: 200 OK 141Response Time: 644.290186ms 142Response Received At: 2015-09-15 12:05:28.922780103 -0700 PDT 143Response Body: { 144 "args": {}, 145 "headers": { 146 "Accept-Encoding": "gzip", 147 "Host": "httpbin.org", 148 "User-Agent": "go-resty v0.1 - https://github.com/go-resty/resty" 149 }, 150 "origin": "0.0.0.0", 151 "url": "http://httpbin.org/get" 152} 153*/ 154``` 155 156#### Enhanced GET 157 158```go 159resp, err := resty.R(). 160 SetQueryParams(map[string]string{ 161 "page_no": "1", 162 "limit": "20", 163 "sort":"name", 164 "order": "asc", 165 "random":strconv.FormatInt(time.Now().Unix(), 10), 166 }). 167 SetHeader("Accept", "application/json"). 168 SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F"). 169 Get("/search_result") 170 171 172// Sample of using Request.SetQueryString method 173resp, err := resty.R(). 174 SetQueryString("productId=232&template=fresh-sample&cat=resty&source=google&kw=buy a lot more"). 175 SetHeader("Accept", "application/json"). 176 SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F"). 177 Get("/show_product") 178``` 179 180#### Various POST method combinations 181 182```go 183// POST JSON string 184// No need to set content type, if you have client level setting 185resp, err := resty.R(). 186 SetHeader("Content-Type", "application/json"). 187 SetBody(`{"username":"testuser", "password":"testpass"}`). 188 SetResult(&AuthSuccess{}). // or SetResult(AuthSuccess{}). 189 Post("https://myapp.com/login") 190 191// POST []byte array 192// No need to set content type, if you have client level setting 193resp, err := resty.R(). 194 SetHeader("Content-Type", "application/json"). 195 SetBody([]byte(`{"username":"testuser", "password":"testpass"}`)). 196 SetResult(&AuthSuccess{}). // or SetResult(AuthSuccess{}). 197 Post("https://myapp.com/login") 198 199// POST Struct, default is JSON content type. No need to set one 200resp, err := resty.R(). 201 SetBody(User{Username: "testuser", Password: "testpass"}). 202 SetResult(&AuthSuccess{}). // or SetResult(AuthSuccess{}). 203 SetError(&AuthError{}). // or SetError(AuthError{}). 204 Post("https://myapp.com/login") 205 206// POST Map, default is JSON content type. No need to set one 207resp, err := resty.R(). 208 SetBody(map[string]interface{}{"username": "testuser", "password": "testpass"}). 209 SetResult(&AuthSuccess{}). // or SetResult(AuthSuccess{}). 210 SetError(&AuthError{}). // or SetError(AuthError{}). 211 Post("https://myapp.com/login") 212 213// POST of raw bytes for file upload. For example: upload file to Dropbox 214fileBytes, _ := ioutil.ReadFile("/Users/jeeva/mydocument.pdf") 215 216// See we are not setting content-type header, since go-resty automatically detects Content-Type for you 217resp, err := resty.R(). 218 SetBody(fileBytes). 219 SetContentLength(true). // Dropbox expects this value 220 SetAuthToken("<your-auth-token>"). 221 SetError(&DropboxError{}). // or SetError(DropboxError{}). 222 Post("https://content.dropboxapi.com/1/files_put/auto/resty/mydocument.pdf") // for upload Dropbox supports PUT too 223 224// Note: resty detects Content-Type for request body/payload if content type header is not set. 225// * For struct and map data type defaults to 'application/json' 226// * Fallback is plain text content type 227``` 228 229#### Sample PUT 230 231You can use various combinations of `PUT` method call like demonstrated for `POST`. 232 233```go 234// Note: This is one sample of PUT method usage, refer POST for more combination 235 236// Request goes as JSON content type 237// No need to set auth token, error, if you have client level settings 238resp, err := resty.R(). 239 SetBody(Article{ 240 Title: "go-resty", 241 Content: "This is my article content, oh ya!", 242 Author: "Jeevanandam M", 243 Tags: []string{"article", "sample", "resty"}, 244 }). 245 SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD"). 246 SetError(&Error{}). // or SetError(Error{}). 247 Put("https://myapp.com/article/1234") 248``` 249 250#### Sample PATCH 251 252You can use various combinations of `PATCH` method call like demonstrated for `POST`. 253 254```go 255// Note: This is one sample of PUT method usage, refer POST for more combination 256 257// Request goes as JSON content type 258// No need to set auth token, error, if you have client level settings 259resp, err := resty.R(). 260 SetBody(Article{ 261 Tags: []string{"new tag1", "new tag2"}, 262 }). 263 SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD"). 264 SetError(&Error{}). // or SetError(Error{}). 265 Patch("https://myapp.com/articles/1234") 266``` 267 268#### Sample DELETE, HEAD, OPTIONS 269 270```go 271// DELETE a article 272// No need to set auth token, error, if you have client level settings 273resp, err := resty.R(). 274 SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD"). 275 SetError(&Error{}). // or SetError(Error{}). 276 Delete("https://myapp.com/articles/1234") 277 278// DELETE a articles with payload/body as a JSON string 279// No need to set auth token, error, if you have client level settings 280resp, err := resty.R(). 281 SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD"). 282 SetError(&Error{}). // or SetError(Error{}). 283 SetHeader("Content-Type", "application/json"). 284 SetBody(`{article_ids: [1002, 1006, 1007, 87683, 45432] }`). 285 Delete("https://myapp.com/articles") 286 287// HEAD of resource 288// No need to set auth token, if you have client level settings 289resp, err := resty.R(). 290 SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD"). 291 Head("https://myapp.com/videos/hi-res-video") 292 293// OPTIONS of resource 294// No need to set auth token, if you have client level settings 295resp, err := resty.R(). 296 SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD"). 297 Options("https://myapp.com/servers/nyc-dc-01") 298``` 299 300### Multipart File(s) upload 301 302#### Using io.Reader 303 304```go 305profileImgBytes, _ := ioutil.ReadFile("/Users/jeeva/test-img.png") 306notesBytes, _ := ioutil.ReadFile("/Users/jeeva/text-file.txt") 307 308resp, err := dclr(). 309 SetFileReader("profile_img", "test-img.png", bytes.NewReader(profileImgBytes)). 310 SetFileReader("notes", "text-file.txt", bytes.NewReader(notesBytes)). 311 SetFormData(map[string]string{ 312 "first_name": "Jeevanandam", 313 "last_name": "M", 314 }). 315 Post(t"http://myapp.com/upload") 316``` 317 318#### Using File directly from Path 319 320```go 321// Single file scenario 322resp, err := resty.R(). 323 SetFile("profile_img", "/Users/jeeva/test-img.png"). 324 Post("http://myapp.com/upload") 325 326// Multiple files scenario 327resp, err := resty.R(). 328 SetFiles(map[string]string{ 329 "profile_img": "/Users/jeeva/test-img.png", 330 "notes": "/Users/jeeva/text-file.txt", 331 }). 332 Post("http://myapp.com/upload") 333 334// Multipart of form fields and files 335resp, err := resty.R(). 336 SetFiles(map[string]string{ 337 "profile_img": "/Users/jeeva/test-img.png", 338 "notes": "/Users/jeeva/text-file.txt", 339 }). 340 SetFormData(map[string]string{ 341 "first_name": "Jeevanandam", 342 "last_name": "M", 343 "zip_code": "00001", 344 "city": "my city", 345 "access_token": "C6A79608-782F-4ED0-A11D-BD82FAD829CD", 346 }). 347 Post("http://myapp.com/profile") 348``` 349 350#### Sample Form submission 351 352```go 353// just mentioning about POST as an example with simple flow 354// User Login 355resp, err := resty.R(). 356 SetFormData(map[string]string{ 357 "username": "jeeva", 358 "password": "mypass", 359 }). 360 Post("http://myapp.com/login") 361 362// Followed by profile update 363resp, err := resty.R(). 364 SetFormData(map[string]string{ 365 "first_name": "Jeevanandam", 366 "last_name": "M", 367 "zip_code": "00001", 368 "city": "new city update", 369 }). 370 Post("http://myapp.com/profile") 371 372// Multi value form data 373criteria := url.Values{ 374 "search_criteria": []string{"book", "glass", "pencil"}, 375} 376resp, err := resty.R(). 377 SetMultiValueFormData(criteria). 378 Post("http://myapp.com/search") 379``` 380 381#### Save HTTP Response into File 382 383```go 384// Setting output directory path, If directory not exists then resty creates one! 385// This is optional one, if you're planning using absoule path in 386// `Request.SetOutput` and can used together. 387resty.SetOutputDirectory("/Users/jeeva/Downloads") 388 389// HTTP response gets saved into file, similar to curl -o flag 390_, err := resty.R(). 391 SetOutput("plugin/ReplyWithHeader-v5.1-beta.zip"). 392 Get("http://bit.ly/1LouEKr") 393 394// OR using absolute path 395// Note: output directory path is not used for absoulte path 396_, err := resty.R(). 397 SetOutput("/MyDownloads/plugin/ReplyWithHeader-v5.1-beta.zip"). 398 Get("http://bit.ly/1LouEKr") 399``` 400 401#### Request URL Path Params 402 403Resty provides easy to use dynamic request URL path params. Params can be set at client and request level. Client level params value can be overridden at request level. 404 405```go 406resty.R().SetPathParams(map[string]string{ 407 "userId": "sample@sample.com", 408 "subAccountId": "100002", 409}). 410Get("/v1/users/{userId}/{subAccountId}/details") 411 412// Result: 413// Composed URL - /v1/users/sample@sample.com/100002/details 414``` 415 416#### Request and Response Middleware 417 418Resty provides middleware ability to manipulate for Request and Response. It is more flexible than callback approach. 419 420```go 421// Registering Request Middleware 422resty.OnBeforeRequest(func(c *resty.Client, req *resty.Request) error { 423 // Now you have access to Client and current Request object 424 // manipulate it as per your need 425 426 return nil // if its success otherwise return error 427 }) 428 429// Registering Response Middleware 430resty.OnAfterResponse(func(c *resty.Client, resp *resty.Response) error { 431 // Now you have access to Client and current Response object 432 // manipulate it as per your need 433 434 return nil // if its success otherwise return error 435 }) 436``` 437 438#### Redirect Policy 439 440Resty provides few ready to use redirect policy(s) also it supports multiple policies together. 441 442```go 443// Assign Client Redirect Policy. Create one as per you need 444resty.SetRedirectPolicy(resty.FlexibleRedirectPolicy(15)) 445 446// Wanna multiple policies such as redirect count, domain name check, etc 447resty.SetRedirectPolicy(resty.FlexibleRedirectPolicy(20), 448 resty.DomainCheckRedirectPolicy("host1.com", "host2.org", "host3.net")) 449``` 450 451##### Custom Redirect Policy 452 453Implement [RedirectPolicy](redirect.go#L20) interface and register it with resty client. Have a look [redirect.go](redirect.go) for more information. 454 455```go 456// Using raw func into resty.SetRedirectPolicy 457resty.SetRedirectPolicy(resty.RedirectPolicyFunc(func(req *http.Request, via []*http.Request) error { 458 // Implement your logic here 459 460 // return nil for continue redirect otherwise return error to stop/prevent redirect 461 return nil 462})) 463 464//--------------------------------------------------- 465 466// Using struct create more flexible redirect policy 467type CustomRedirectPolicy struct { 468 // variables goes here 469} 470 471func (c *CustomRedirectPolicy) Apply(req *http.Request, via []*http.Request) error { 472 // Implement your logic here 473 474 // return nil for continue redirect otherwise return error to stop/prevent redirect 475 return nil 476} 477 478// Registering in resty 479resty.SetRedirectPolicy(CustomRedirectPolicy{/* initialize variables */}) 480``` 481 482#### Custom Root Certificates and Client Certificates 483 484```go 485// Custom Root certificates, just supply .pem file. 486// you can add one or more root certificates, its get appended 487resty.SetRootCertificate("/path/to/root/pemFile1.pem") 488resty.SetRootCertificate("/path/to/root/pemFile2.pem") 489// ... and so on! 490 491// Adding Client Certificates, you add one or more certificates 492// Sample for creating certificate object 493// Parsing public/private key pair from a pair of files. The files must contain PEM encoded data. 494cert1, err := tls.LoadX509KeyPair("certs/client.pem", "certs/client.key") 495if err != nil { 496 log.Fatalf("ERROR client certificate: %s", err) 497} 498// ... 499 500// You add one or more certificates 501resty.SetCertificates(cert1, cert2, cert3) 502``` 503 504#### Proxy Settings - Client as well as at Request Level 505 506Default `Go` supports Proxy via environment variable `HTTP_PROXY`. Resty provides support via `SetProxy` & `RemoveProxy`. 507Choose as per your need. 508 509**Client Level Proxy** settings applied to all the request 510 511```go 512// Setting a Proxy URL and Port 513resty.SetProxy("http://proxyserver:8888") 514 515// Want to remove proxy setting 516resty.RemoveProxy() 517``` 518 519#### Retries 520 521Resty uses [backoff](http://www.awsarchitectureblog.com/2015/03/backoff.html) 522to increase retry intervals after each attempt. 523 524Usage example: 525 526```go 527// Retries are configured per client 528resty. 529 // Set retry count to non zero to enable retries 530 SetRetryCount(3). 531 // You can override initial retry wait time. 532 // Default is 100 milliseconds. 533 SetRetryWaitTime(5 * time.Second). 534 // MaxWaitTime can be overridden as well. 535 // Default is 2 seconds. 536 SetRetryMaxWaitTime(20 * time.Second) 537``` 538 539Above setup will result in resty retrying requests returned non nil error up to 5403 times with delay increased after each attempt. 541 542You can optionally provide client with custom retry conditions: 543 544```go 545resty.AddRetryCondition( 546 // Condition function will be provided with *resty.Response as a 547 // parameter. It is expected to return (bool, error) pair. Resty will retry 548 // in case condition returns true or non nil error. 549 func(r *resty.Response) (bool, error) { 550 return r.StatusCode() == http.StatusTooManyRequests, nil 551 }, 552) 553``` 554 555Above example will make resty retry requests ended with `429 Too Many Requests` 556status code. 557 558Multiple retry conditions can be added. 559 560It is also possible to use `resty.Backoff(...)` to get arbitrary retry scenarios 561implemented. [Reference](retry_test.go). 562 563#### Choose REST or HTTP mode 564 565```go 566// REST mode. This is Default. 567resty.SetRESTMode() 568 569// HTTP mode 570resty.SetHTTPMode() 571``` 572 573#### Allow GET request with Payload 574 575```go 576// Allow GET request with Payload. This is disabled by default. 577resty.SetAllowGetMethodPayload(true) 578``` 579 580#### Wanna Multiple Clients 581 582```go 583// Here you go! 584// Client 1 585client1 := resty.New() 586client1.R().Get("http://httpbin.org") 587// ... 588 589// Client 2 590client2 := resty.New() 591client2.R().Head("http://httpbin.org") 592// ... 593 594// Bend it as per your need!!! 595``` 596 597#### Remaining Client Settings & its Options 598 599```go 600// Unique settings at Client level 601//-------------------------------- 602// Enable debug mode 603resty.SetDebug(true) 604 605// Using you custom log writer 606logFile, _ := os.OpenFile("/Users/jeeva/go-resty.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) 607resty.SetLogger(logFile) 608 609// Assign Client TLSClientConfig 610// One can set custom root-certificate. Refer: http://golang.org/pkg/crypto/tls/#example_Dial 611resty.SetTLSClientConfig(&tls.Config{ RootCAs: roots }) 612 613// or One can disable security check (https) 614resty.SetTLSClientConfig(&tls.Config{ InsecureSkipVerify: true }) 615 616// Set client timeout as per your need 617resty.SetTimeout(1 * time.Minute) 618 619 620// You can override all below settings and options at request level if you want to 621//-------------------------------------------------------------------------------- 622// Host URL for all request. So you can use relative URL in the request 623resty.SetHostURL("http://httpbin.org") 624 625// Headers for all request 626resty.SetHeader("Accept", "application/json") 627resty.SetHeaders(map[string]string{ 628 "Content-Type": "application/json", 629 "User-Agent": "My custom User Agent String", 630 }) 631 632// Cookies for all request 633resty.SetCookie(&http.Cookie{ 634 Name:"go-resty", 635 Value:"This is cookie value", 636 Path: "/", 637 Domain: "sample.com", 638 MaxAge: 36000, 639 HttpOnly: true, 640 Secure: false, 641 }) 642resty.SetCookies(cookies) 643 644// URL query parameters for all request 645resty.SetQueryParam("user_id", "00001") 646resty.SetQueryParams(map[string]string{ // sample of those who use this manner 647 "api_key": "api-key-here", 648 "api_secert": "api-secert", 649 }) 650resty.R().SetQueryString("productId=232&template=fresh-sample&cat=resty&source=google&kw=buy a lot more") 651 652// Form data for all request. Typically used with POST and PUT 653resty.SetFormData(map[string]string{ 654 "access_token": "BC594900-518B-4F7E-AC75-BD37F019E08F", 655 }) 656 657// Basic Auth for all request 658resty.SetBasicAuth("myuser", "mypass") 659 660// Bearer Auth Token for all request 661resty.SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F") 662 663// Enabling Content length value for all request 664resty.SetContentLength(true) 665 666// Registering global Error object structure for JSON/XML request 667resty.SetError(&Error{}) // or resty.SetError(Error{}) 668``` 669 670#### Unix Socket 671 672```go 673unixSocket := "/var/run/my_socket.sock" 674 675// Create a Go's http.Transport so we can set it in resty. 676transport := http.Transport{ 677 Dial: func(_, _ string) (net.Conn, error) { 678 return net.Dial("unix", unixSocket) 679 }, 680} 681 682// Set the previous transport that we created, set the scheme of the communication to the 683// socket and set the unixSocket as the HostURL. 684r := resty.New().SetTransport(&transport).SetScheme("http").SetHostURL(unixSocket) 685 686// No need to write the host's URL on the request, just the path. 687r.R().Get("/index.html") 688``` 689 690#### Bazel support 691 692Resty can be built, tested and depended upon via [Bazel](https://bazel.build). 693For example, to run all tests: 694 695```shell 696bazel test :go_default_test 697``` 698 699#### Mocking http requests using [httpmock](https://github.com/jarcoal/httpmock) library 700 701In order to mock the http requests when testing your application you 702could use the `httpmock` library. 703 704When using the default resty client, you should pass the client to the library as follow: 705 706```go 707httpmock.ActivateNonDefault(resty.DefaultClient.GetClient()) 708``` 709 710More detailed example of mocking resty http requests using ginko could be found [here](https://github.com/jarcoal/httpmock#ginkgo--resty-example). 711 712## Versioning 713 714resty releases versions according to [Semantic Versioning](http://semver.org) 715 716 * `gopkg.in/resty.vX` points to appropriate tagged versions; `X` denotes version series number and it's a stable release for production use. For e.g. `gopkg.in/resty.v0`. 717 * Development takes place at the master branch. Although the code in master should always compile and test successfully, it might break API's. I aim to maintain backwards compatibility, but sometimes API's and behavior might be changed to fix a bug. 718 719## Contribution 720 721I would welcome your contribution! If you find any improvement or issue you want to fix, feel free to send a pull request, I like pull requests that include test cases for fix/enhancement. I have done my best to bring pretty good code coverage. Feel free to write tests. 722 723BTW, I'd like to know what you think about `Resty`. Kindly open an issue or send me an email; it'd mean a lot to me. 724 725## Creator 726 727[Jeevanandam M.](https://github.com/jeevatkm) (jeeva@myjeeva.com) 728 729## Contributors 730 731Have a look on [Contributors](https://github.com/go-resty/resty/graphs/contributors) page. 732 733## License 734 735Resty released under MIT license, refer [LICENSE](LICENSE) file. 736