goreq: 極簡單的流式golang的http客戶端
goreq 是一個極其簡單的流式golang http client。它是我尋找類似Java OKHttp庫的golang http client庫時創建的。
最原始的代碼fork自 gorequest ,它實現了Node.js庫 SuperAgent 類似的功能。但是gorequest有一些bug沒有fix,用戶也提出了一些新的特性沒有支持。
我重構了代碼,更正了一些bug,增加了新的特性,尤其是POST BODY現在可以支持任意類型, 不再局限于json或者form字符串格式。 因為改動比較大,不好提交pull requests,干脆創建了一個新的輪子。這就是這個項目的最初目的。
比如下面調用baidu API根據IP地址獲取地理信息的例子:
headers := `{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0",
"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Referer":"http://developer.baidu.com/map/index.php?title=webapi/ip-api"}`
_, body, _ := goreq.New().SetHeaders(headers).Get( "http://api.map.baidu.com/location/ip?ak=E4805d16520de693a3fe707cdc962045&ip=202.198.16.3&coor=bd09ll" ).End()
支持的HTTP METHOD
支持 GET, POST, HEAD, PUT, DELETE, PATCH 等http method,而且都想HTTP GET一樣簡單, 比如下面的HTTP PUT:
_, body, _ := goreq.New().Put( "http://httpbin.org/put" ).SendRawString( "hello world" ).End()
println (body)
輸出結果:
{
" args ": {} ,
" data ": "hello world" ,
" files ": {} ,
" form ": {} ,
" headers ": {
" Accept-Encoding ": "gzip" ,
" Content-Length ": "11" ,
" Content-Type ": "text/plain" ,
" Host ": "httpbin.org" ,
" User-Agent ": "Go-http-client/1.1"
},
" json ": null ,
" origin ": "117.121.34.13" ,
" url ": "http://httpbin.org/put"
}
Request Body及Header
發送一個JSON格式的內容也很簡單, 你可以傳入一個struct, GoReq自動將它轉為一個JSON字符串。
_, body, _ := goreq.New().Put( "http://httpbin.org/put" ).SendMapString( "name=Baymax&password=12345678" ).End()
注意在這種情況下(設置了body,未設置Content-Type), Content-Type為application/json。
甚至你可以傳遞一個查詢字符串:
_, body, _ := goreq.New().Put( "http://httpbin.org/put" ).ContentType( "json" ).SendMapString( "name=Baymax&password=12345678" ).End()
注意在這種情況下(設置了body,未設置Content-Type), Content-Type為application/x-www-form-urlencoded。所以這里顯示地設置為"application/json"
Proxy和超時
可以為讀寫設置一個超時時間:
_, _, err := goreq.New().Get( "http://httpbin.org//delay/100" ).Timeout (10 * time.Second).End()
println (err [0 ].Error())
Basic Auth
GoReq支持Basic Auth身份驗證:
_, body, _ := goreq.New().Get( "http://httpbin.org/basic-auth/Baymax/12345678" ).SetBasicAuth( "Baymax" , "12345678" ).End()
更多的例子和文檔請查看 godoc