Giter Site home page Giter Site logo

goreq's Introduction

Build Status

GoReq

Simple and sane HTTP request library for Go language.

Table of Contents

Why GoReq?

Go has very nice native libraries that allows you to do lots of cool things. But sometimes those libraries are too low level, which means that to do a simple thing, like an HTTP Request, it takes some time. And if you want to do something as simple as adding a timeout to a request, you will end up writing several lines of code.

This is why we think GoReq is useful. Because you can do all your HTTP requests in a very simple and comprehensive way, while enabling you to do more advanced stuff by giving you access to the native API.

How do I install it?

go get github.com/franela/goreq

What can I do with it?

Making requests with different methods

GET

res, err := goreq.Request{ Uri: "http://www.google.com" }.Do()

GoReq default method is GET.

You can also set value to GET method easily

type Item struct {
        Limit int
        Skip int
        Fields string
}

item := Item {
        Limit: 3,
        Skip: 5,
        Fields: "Value",
}

res, err := goreq.Request{
        Uri: "http://localhost:3000/",
        QueryString: item,
}.Do()

The sample above will send http://localhost:3000/?limit=3&skip=5&fields=Value

Alternatively the url tag can be used in struct fields to define the parameter value to avoid forcing variable names

type Item struct {
        TheLimit int `url:"the_limit"`
        TheSkip int `url:"the_skip"`
        TheFields string `url:"the_field"`
}

item := Item {
        TheLimit: 3,
        TheSkip: 5,
        TheFields: "Value",
}

res, err := goreq.Request{
        Uri: "http://localhost:3000/",
        QueryString: item,
}.Do()

The sample above will send http://localhost:3000/?the_limit=3&the_skip=5&the_field=Value

QueryString also support url.Values

item := url.Values{}
item.Set("Limit", 3)
item.Add("Field", "somefield")
item.Add("Field", "someotherfield")

res, err := goreq.Request{
        Uri: "http://localhost:3000/",
        QueryString: item,
}.Do()

The sample above will send http://localhost:3000/?limit=3&field=somefield&field=someotherfield

POST

res, err := goreq.Request{ Method: "POST", Uri: "http://www.google.com" }.Do()

Sending payloads in the Body

You can send string, Reader or interface{} in the body. The first two will be sent as text. The last one will be marshalled to JSON, if possible.

type Item struct {
    Id int
    Name string
}

item := Item{ Id: 1111, Name: "foobar" }

res, err := goreq.Request{
    Method: "POST",
    Uri: "http://www.google.com",
    Body: item,
}.Do()

Specifiying request headers

We think that most of the times the request headers that you use are: Host, Content-Type, Accept and User-Agent. This is why we decided to make it very easy to set these headers.

res, err := Request{
    Uri: "http://www.google.com",
    Host: "foobar.com",
    Accept: "application/json",
    ContentType: "application/json",
    UserAgent: "goreq",
}.Do()

But sometimes you need to set other headers. You can still do it.

req := Request{ Uri: "http://www.google.com" }

req.AddHeader("X-Custom", "somevalue")

req.Do()

Alternatively you can use the WithHeader function to keep the syntax short

res, err = Request{ Uri: "http://www.google.com" }.WithHeader("X-Custom", "somevalue").Do()

Cookie support

Cookies can be either set at the request level by sending a CookieJar in the CookieJar request field or you can use goreq's one-liner WithCookie method as shown below

res, err := Request{
    Uri: "http://www.google.com",
}.
WithCookie(&http.Cookie{Name: "c1", Value: "v1"}).
Do()

Setting timeouts

GoReq supports 2 kind of timeouts. A general connection timeout and a request specific one. By default the connection timeout is of 1 second. There is no default for request timeout, which means it will wait forever.

You can change the connection timeout doing:

goreq.SetConnectTimeout(100 * time.Millisecond)

And specify the request timeout doing:

res, err := goreq.Request{
    Uri: "http://www.google.com",
    Timeout: 500 * time.Millisecond,
}.Do()

Using the Response and Error

GoReq will always return 2 values: a Response and an Error. If Error is not nil it means that an error happened while doing the request and you shouldn't use the Response in any way. You can check what happened by getting the error message:

fmt.Println(err.Error())

And to make it easy to know if it was a timeout error, you can ask the error or return it:

if serr, ok := err.(*goreq.Error); ok {
    if serr.Timeout() {
        ...
    }
}
return err

If you don't get an error, you can safely use the Response.

res.Uri // return final URL location of the response (fulfilled after redirect was made)
res.StatusCode // return the status code of the response
res.Body // gives you access to the body
res.Body.ToString() // will return the body as a string
res.Header.Get("Content-Type") // gives you access to all the response headers

Remember that you should always close res.Body if it's not nil

Receiving JSON

GoReq will help you to receive and unmarshal JSON.

type Item struct {
    Id int
    Name string
}

var item Item

res.Body.FromJsonTo(&item)

Sending/Receiving Compressed Payloads

GoReq supports gzip, deflate and zlib compression of requests' body and transparent decompression of responses provided they have a correct Content-Encoding header.

#####Using gzip compression:

res, err := goreq.Request{
    Method: "POST",
    Uri: "http://www.google.com",
    Body: item,
    Compression: goreq.Gzip(),
}.Do()

#####Using deflate compression:

res, err := goreq.Request{
    Method: "POST",
    Uri: "http://www.google.com",
    Body: item,
    Compression: goreq.Deflate(),
}.Do()

#####Using zlib compression:

res, err := goreq.Request{
    Method: "POST",
    Uri: "http://www.google.com",
    Body: item,
    Compression: goreq.Zlib(),
}.Do()

#####Using compressed responses: If servers replies a correct and matching Content-Encoding header (gzip requires Content-Encoding: gzip and deflate Content-Encoding: deflate) goreq transparently decompresses the response so the previous example should always work:

type Item struct {
    Id int
    Name string
}
res, err := goreq.Request{
    Method: "POST",
    Uri: "http://www.google.com",
    Body: item,
    Compression: goreq.Gzip(),
}.Do()
var item Item
res.Body.FromJsonTo(&item)

If no Content-Encoding header is replied by the server GoReq will return the crude response.

Proxy

If you need to use a proxy for your requests GoReq supports the standard http_proxy env variable as well as manually setting the proxy for each request

res, err := goreq.Request{
    Method: "GET",
    Proxy: "http://myproxy:myproxyport",
    Uri: "http://www.google.com",
}.Do()

Proxy basic auth is also supported

res, err := goreq.Request{
    Method: "GET",
    Proxy: "http://user:pass@myproxy:myproxyport",
    Uri: "http://www.google.com",
}.Do()

Debug

If you need to debug your http requests, it can print the http request detail.

res, err := goreq.Request{
	Method:      "GET",
	Uri:         "http://www.google.com",
	Compression: goreq.Gzip(),
	ShowDebug:   true,
}.Do()
fmt.Println(res, err)

and it will print the log:

GET / HTTP/1.1
Host: www.google.com
Accept:
Accept-Encoding: gzip
Content-Encoding: gzip
Content-Type:

TODO:

We do have a couple of issues pending we'll be addressing soon. But feel free to contribute and send us PRs (with tests please ๐Ÿ˜„).

goreq's People

Contributors

bfontaine avatar chilijung avatar defia avatar ezbercih avatar jefftexture avatar jimzhan avatar laiwei avatar marcosnils avatar mtsgrd avatar oylenshpeegul avatar ryansb avatar sschepens avatar xetorthio avatar

Watchers

 avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.