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