• Stars
    star
    465
  • Rank 94,287 (Top 2 %)
  • Language
    Go
  • License
    MIT License
  • Created almost 11 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Advanced HTTP client for golang

go-httpclient

Travis godoc License Go Report Card Coverage Status

Advanced HTTP client for golang.

Features

  • Chainable API
  • Direct file upload
  • Timeout
  • HTTP Proxy
  • Cookie
  • GZIP
  • Redirect Policy
  • Cancel(with context)

Installation

go get github.com/ddliu/go-httpclient

Quick Start

package main

import (
    "github.com/ddliu/go-httpclient"
)

func main() {
    httpclient.Defaults(httpclient.Map {
        httpclient.OPT_USERAGENT: "my awsome httpclient",
        "Accept-Language": "en-us",
    })

    res, err := httpclient.Get("http://google.com/search", map[string]string{
        "q": "news",
    })

    println(res.StatusCode, err)
}

Usage

Setup

Use httpclient.Defaults to setup default behaviors of the HTTP client.

httpclient.Defaults(httpclient.Map {
    httpclient.OPT_USERAGENT: "my awsome httpclient",
    "Accept-Language": "en-us",
})

The OPT_XXX options define basic behaviours of this client, other values are default request headers of this request. They are shared between different HTTP requests.

Sending Request

// get
httpclient.Get("http://httpbin.org/get", map[string]string{
    "q": "news",
})

// get with url.Values
httpclient.Get("http://httpbin.org/get", url.Values{
    "q": []string{"news", "today"}
})

// post
httpclient.Post("http://httpbin.org/post", map[string]string {
    "name": "value"
})

// post file(multipart)
httpclient.Post("http://httpbin.org/multipart", map[string]string {
    "@file": "/tmp/hello.pdf",
})

// put json
httpclient.PutJson("http://httpbin.org/put", 
`{
    "name": "hello",
}`)

// delete
httpclient.Delete("http://httpbin.org/delete")

// options
httpclient.Options("http://httpbin.org")

// head
httpclient.Head("http://httpbin.org/get")

Customize Request

Before you start a new HTTP request with Get or Post method, you can specify temporary options, headers or cookies for current request.

httpclient.
    WithHeader("User-Agent", "Super Robot").
    WithHeader("custom-header", "value").
    WithHeaders(map[string]string {
        "another-header": "another-value",
        "and-another-header": "another-value",
    }).
    WithOption(httpclient.OPT_TIMEOUT, 60).
    WithCookie(&http.Cookie{
        Name: "uid",
        Value: "123",
    }).
    Get("http://github.com")

Response

The httpclient.Response is a thin wrap of http.Response.

// traditional
res, err := httpclient.Get("http://google.com")
bodyBytes, err := ioutil.ReadAll(res.Body)
res.Body.Close()

// ToString
res, err = httpclient.Get("http://google.com")
bodyString, err := res.ToString()

// ReadAll
res, err = httpclient.Get("http://google.com")
bodyBytes, err := res.ReadAll()

Handle Cookies

url := "http://github.com"
httpclient.
    WithCookie(&http.Cookie{
        Name: "uid",
        Value: "123",
    }).
    Get(url)

for _, cookie := range httpclient.Cookies() {
    fmt.Println(cookie.Name, cookie.Value)
}

for k, v := range httpclient.CookieValues() {
    fmt.Println(k, v)
}

fmt.Println(httpclient.CookieValue("uid"))

Concurrent Safe

If you want to start many requests concurrently, remember to call the Begin method when you begin:

go func() {
    httpclient.
        Begin().
        WithHeader("Req-A", "a").
        Get("http://google.com")
}()
go func() {
    httpclient.
        Begin().
        WithHeader("Req-B", "b").
        Get("http://google.com")
}()

Error Checking

You can use httpclient.IsTimeoutError to check for timeout error:

res, err := httpclient.Get("http://google.com")
if httpclient.IsTimeoutError(err) {
    // do something
}

Full Example

See examples/main.go

Options

Available options as below:

  • OPT_FOLLOWLOCATION: TRUE to follow any "Location: " header that the server sends as part of the HTTP header. Default to true.
  • OPT_CONNECTTIMEOUT: The number of seconds or interval (with time.Duration) to wait while trying to connect. Use 0 to wait indefinitely.
  • OPT_CONNECTTIMEOUT_MS: The number of milliseconds to wait while trying to connect. Use 0 to wait indefinitely.
  • OPT_MAXREDIRS: The maximum amount of HTTP redirections to follow. Use this option alongside OPT_FOLLOWLOCATION.
  • OPT_PROXYTYPE: Specify the proxy type. Valid options are PROXY_HTTP, PROXY_SOCKS4, PROXY_SOCKS5, PROXY_SOCKS4A. Only PROXY_HTTP is supported currently.
  • OPT_TIMEOUT: The maximum number of seconds or interval (with time.Duration) to allow httpclient functions to execute.
  • OPT_TIMEOUT_MS: The maximum number of milliseconds to allow httpclient functions to execute.
  • OPT_COOKIEJAR: Set to true to enable the default cookiejar, or you can set to a http.CookieJar instance to use a customized jar. Default to true.
  • OPT_INTERFACE: TODO
  • OPT_PROXY: Proxy host and port(127.0.0.1:1080).
  • OPT_REFERER: The Referer header of the request.
  • OPT_USERAGENT: The User-Agent header of the request. Default to "go-httpclient v{{VERSION}}".
  • OPT_REDIRECT_POLICY: Function to check redirect.
  • OPT_PROXY_FUNC: Function to specify proxy.
  • OPT_UNSAFE_TLS: Set to true to disable TLS certificate checking.
  • OPT_DEBUG: Print request info.
  • OPT_CONTEXT: Set context.context (can be used to cancel request).
  • OPT_BEFORE_REQUEST_FUNC: Function to call before request is sent, option should be type func(*http.Client, *http.Request).

Seperate Clients

By using the httpclient.Get, httpclient.Post methods etc, you are using a default shared HTTP client.

If you need more than one client in a single programme. Just create and use them seperately.

c1 := httpclient.NewHttpClient().Defaults(httpclient.Map {
    httpclient.OPT_USERAGENT: "browser1",
})

c1.Get("http://google.com/")

c2 := httpclient.NewHttpClient().Defaults(httpclient.Map {
    httpclient.OPT_USERAGENT: "browser2",
})

c2.Get("http://google.com/")

More Repositories

1

motto

Nodejs module environment in golang(based on otto)
JavaScript
93
star
2

node-svn-spawn

Easy way to access svn repository with node.js.
JavaScript
89
star
3

gulp-remote-src

Remote gulp.src
JavaScript
20
star
4

cn-mirror-awesome

镜像类资源集
20
star
5

spider

A flexible spider in PHP
PHP
19
star
6

nodego

Node.js in golang (experimental)
Go
18
star
7

grunt-push-svn

Push local directory to a specified SVN server
JavaScript
14
star
8

tinyark

Tiny PHP framework for open platforms
PHP
6
star
9

go-dict

go-dict is a golang package to manage and lookup a local dictionary.
Go
5
star
10

php-wxpay

微信支付PHP SDK
PHP
4
star
11

sae-drupal

Drupal for SAE
PHP
4
star
12

gulp-gobin

Convert any file into managable Go source code (like go-bindata).
JavaScript
4
star
13

go-spider

A flexible spider as well as a general perposed task runner.
Go
4
star
14

go-requery

Query text with the power of Regexp
Go
3
star
15

tinydb

Lightweight database library on top of PDO
PHP
3
star
16

php-alipay

支付宝PHP SDK
PHP
3
star
17

php-wildcards

Simple wildcards in PHP
PHP
2
star
18

requery

Query text data with the power of Regular Expression.
PHP
2
star
19

docker-ubuntu

Snippets and sample Dockerfiles to help build Ubuntu based images faster.
Shell
2
star
20

pyark

Python toolkit that ease your development
Python
2
star
21

go-httpreplay

Marshal and unmarshal request/response, so that it can be persisted or replayed any time.
Go
2
star
22

node-easy-spawn

Utilities that make it easier to write child_process.spawn programmes
JavaScript
2
star
23

goption

Option container for golang
Go
2
star
24

weipan-sdk-python

Weipan Python SDK
Python
2
star
25

http-monkey

Continuous HTTP request for network simulation.
Shell
1
star
26

break-reminder

Python
1
star
27

ghosts

GHosts - Efficient hosts switcher
Go
1
star
28

pytranslate

Simple python translate program
Python
1
star
29

fractal

Fractal is a Go package that makes it easy to work with dynamic and nested data types, with encoding/decoding support.
Go
1
star
30

go-compact

Merge external js/css/image files into HTML as a single file
Go
1
star
31

go-combiner

go-combiner is a golang package to combine strings
Go
1
star
32

normurl

Normalize URL
PHP
1
star
33

grunt-cmd-text

Convert text file to cmd module so that it can be required by cmd loaders
JavaScript
1
star
34

dockerfiles

Shell
1
star
35

go-dbless

Database library with less complexity and less modeling.
Go
1
star
36

webhook

Feature rich webhook made easy
Go
1
star
37

airdoc

Serve markdown document on the air
PHP
1
star