Go语言HttpRequest项目源码地址: https://github.com/kirinlabs/HttpRequest

主要实现功能

  1. 支持常用的GET、POST、DELETE、PUT等
  2. GET 除了正常请求url,也可以附带”name=flyfreely&address=beijing”或者map[string]interface{} 两种参数,包会自动整合到QueryString中
  3. POST 支持string, []byte, bytes.Reader, bytes.Buffer, *strings.Reader, map[string]interface{}等参数; 如果发送JSON请求,几乎可以支持发送所有数据类型。
  4. 具有快速构建Headers、Cookies、设置超时时间、请求、耗时、打印请求信息等功能

安装

  1. go get https://github.com/kirinlabs/HttpRequest

发送请求

导入HttpRequest

  1. import "github.com/kirinlabs/HttpRequest"

实例化:

  1. req := HttpRequest.NewRequest()

然后,尝试获取某个网页。我们来获取 Github 的公共时间线

  1. res,err := req.Get("https://api.github.com/events")

返回一个res的Response对象和err的Error对象

自定义Transport

  1. var transport *http.Transport
  2. func init() {
  3. transport = &http.Transport{
  4. DialContext: (&net.Dialer{
  5. Timeout: 30 * time.Second,
  6. KeepAlive: 30 * time.Second,
  7. DualStack: true,
  8. }).DialContext,
  9. MaxIdleConns: 100,
  10. IdleConnTimeout: 90 * time.Second,
  11. TLSHandshakeTimeout: 5 * time.Second,
  12. ExpectContinueTimeout: 1 * time.Second,
  13. }
  14. }
  15. func demo(){
  16. // Use http.DefaultTransport
  17. res, err := HttpRequest.Get("http://127.0.0.1:8080")
  18. // Use custom Transport
  19. res, err := HttpRequest.Transport(transport).Get("http://127.0.0.1:8080")
  20. }

Post 请求

  1. //无参请求
  2. res,err := req.Post("https://www.baidu.com")
  3. //发送整数类型
  4. res,err := req.Post("https://www.baidu.com",uint32(100))
  5. //发送[]byte
  6. res,err := req.Post("https://www.baidu.com",[]byte("bytes data"))
  7. //发送*bytes.Reader,*strings.Reader,*bytes.Buffer
  8. data := bytes.NewReader(buf []byte)
  9. res,err := req.Post("https://www.baidu.com",data)
  10. res,err := req.Post("https://www.baidu.com",strings.NewReader("string data"))
  11. //请求体为文本
  12. res,err := req.Post("https://www.baidu.com","hello")
  13. //请求体为Json字符串
  14. res,err := req.Post("https://www.baidu.com","{\"name\":\"github\"}")
  15. //map传参
  16. res.err := req.Post("https://www.baidu.com",map[string]interface{}{
  17. "name":"github",
  18. "type":1,
  19. })

也可以不用实例化,直接发送请求

  1. //快速发送Get请求
  2. res,err := HttpRequest.Get("https://www.baidu.com")
  3. res,err := HttpRequest.Get("https://www.baidu.com","title=baidu")
  4. //快速发送Post请求
  5. res,err := HttpRequest.Post("https://www.baidu.com")
  6. //发送整数类型
  7. res,err := req.Post("https://www.baidu.com",uint32(100))
  8. //发送[]byte
  9. res,err := req.Post("https://www.baidu.com",[]byte("bytes data"))
  10. //发送*bytes.Reader,*strings.Reader,*bytes.Buffer
  11. res,err := req.Post("https://www.baidu.com",bytes.NewReader(buf []byte))
  12. res,err := req.Post("https://www.baidu.com",bytes.NewBuffer(buf []byte))
  13. res,err := req.Post("https://www.baidu.com",strings.NewReader("string data"))
  14. res,err := HttpRequest.Post("https://www.baidu.com","title=baidu&type=pdf")
  15. res,err := HttpRequest.Post("https://www.baidu.com",map[string]interface{}{
  16. "title":"baidu",
  17. })
  18. //快速发送JSON请求
  19. res,err := HttpRequest.JSON().Post("https://www.baidu.com",map[string]interface{}{
  20. "title":"baidu",
  21. })
  22. res,err := HttpRequest.JSON().Post("https://www.baidu.com",`{"title":"baidu","type":"pdf"}`)

传递URL参数

你想为URL的查询字符串(query string)传递数据。如:手工构建URL,http://www.baidu.com/index?key=value。HttpRequest允许你使用第2个参数以字符串”id=100&name=github”或map[string]interface{}{“id”:10,”name”:”github”}字典的形式把数据传递给URL:

手工传参:

  1. res,err := req.Get("https://www.baidu.com/index?name=github")

[

](https://www.baidu.com/index?name=github“))
字符串传参:

  1. res,err := req.Get("https://www.baidu.com/index?name=github","id=100&type=1")

[

](https://www.baidu.com/index?name=github","id=100&type=1“))
map传参:

  1. res,err := req.Get("https://www.baidu.com/index?name=github",map[string]interface{}{
  2. "id":10,
  3. "type":1,
  4. })

响应内容

能读取服务器响应的内容

  1. res,err := req.Post("https://api.github.com/events")

[

](https://api.github.com/events“))
获取服务器返回的内容:

  1. body,err := res.Body()

获取服务器响应状态码:

  1. res.StatusCode()

获取服务器响应Headers:

  1. res.Headers()

返回一个map[string]string的字典

获取请求响应时间:

  1. res.Time()

Json响应内容

HttpRequest内置JSON解码,来解析JSON数据:

  1. //Format the json return value
  2. body, err := res.Json()
  3. fmt.Println(body)

如果JSON解码失败,会返回一个err错误

定制请求头

如果想为请求添加HTTP头部信息,只需要简单的传一个map给SetHeaders方法

  1. req.SetHeaders(map[string]string{
  2. "Content-Type":"application/json",
  3. "Source":"api",
  4. })

注:所有header值必须是字符串,SetHeaders可以多次调用,如果Key重复则会覆盖前面设置的值

BasicAuth 认证

如果想为请求添加HTTP头部信息,只需要简单的传一个map给SetHeaders方法

  1. req.SetBasicAuth("username","password")

CookieJar

  1. j, _ := cookiejar.New(nil)
  2. j.SetCookies(&url.URL{
  3. Scheme: "http",
  4. Host: "127.0.0.1:8000",
  5. }, []*http.Cookie{
  6. &http.Cookie{Name: "identity-user", Value: "83df5154d0ed31d166f5c54ddc"},
  7. &http.Cookie{Name: "token_id", Value: "JSb99d0e7d809610186813583b4f802a37b99d"},
  8. })
  9. res, err := HttpRequest.Jar(j).Get("http://127.0.0.1:8000/city/list")
  10. defer res.Close()
  11. if err != nil {
  12. log.Fatalf("Request error:%v", err.Error())
  13. }

Proxy代理

通过代理Ip访问

  1. proxy, err := url.Parse("http://proxyip:proxyport")
  2. if err != nil {
  3. log.Println(err)
  4. }
  5. res, err := HttpRequest.Proxy(http.ProxyURL(proxy)).Get("http://127.0.0.1:8000/ip")
  6. defer res.Close()
  7. if err != nil {
  8. log.Println("Request error:%v", err.Error())
  9. }
  10. body, err := res.Body()
  11. if err != nil {
  12. log.Println("Get body error:%v", err.Error())
  13. }
  14. log.Println(string(body))

JSON请求

如果想以json方式发送请求,HttpRequest支持2种方式

设置Header头部信息

  1. req.SetHeaders(map[string]string{"Content-Type":"application/json"})
  2. req.Post("https://www.baidu.com","{\"name\":\"github\"}")

调用req.JSON()内置方法

  1. //直接发磅Json字符串参数
  2. res,err := req.JSON().Post("https://www.baidu.com","{\"name\":\"github\"}")
  3. //自动将Map以Json方式发送参数
  4. res,err := req.JSON().Post("https://www.baidu.com",map[string]interface{}{
  5. "name":"github"
  6. })

Cookie

  1. req.SetCookies(map[string]string{
  2. "name":"jason"
  3. })

超时

  1. req.SetTimeout(5)

关闭证书验证

当请求https协议时提示x509: certificate signed by unknown authority时,可关闭证书验证

  1. req.SetTLSClient(&tls.Config{InsecureSkipVerify: true})

调试模式

  1. req.Debug(true)

串行调用

  1. req := HttpRequest.NewRequest().Debug(true).SetTimeout(5).SetHeader()

Respone对象

获取返回的Response对象

  1. resp.Response()

获取返回码

  1. resp.StatusCode()

获取Body主体信息

  1. resp.Body()

返回[]byte和error

获取请求耗时

  1. resp.Time() string //单位是毫秒

获取真实Url

  1. res.Url()

完整示例

  1. package main
  2. import (
  3. "github.com/kirinlabs/HttpRequest"
  4. "fmt"
  5. "log"
  6. )
  7. func main() {
  8. req := HttpRequest.NewRequest()
  9. // 设置超时时间,不设置时,默认30s
  10. req.SetTimeout(5)
  11. // 设置Headers
  12. req.SetHeaders(map[string]string{
  13. "Content-Type": "application/x-www-form-urlencoded", //这也是HttpRequest包的默认设置
  14. })
  15. // 设置Cookies
  16. req.SetCookies(map[string]string{
  17. "sessionid": "LSIE89SFLKGHHASLC9EETFBVNOPOXNM",
  18. })
  19. postData := map[string]interface{}{
  20. "id": 1,
  21. "title": "csdn",
  22. }
  23. // GET 默认调用方法
  24. resp, err := req.Get("http://127.0.0.1:8000?name=flyfreely")
  25. // GET 传参调用方法
  26. // 第2个参数默认为nil,也可以传参map[string]interface{}
  27. // 第2个参数不为nil时,会把传入的map以query传参的形式重新构造新url
  28. // 新的URL: http://127.0.0.1:8000?name=flyfreely&id=1&title=csdn
  29. //resp, err := req.Get("http://127.0.0.1:8000?name=flyfreely", postData)
  30. // POST 调用方法
  31. //resp, err := req.Post("http://127.0.0.1:8000", postData)
  32. if err != nil {
  33. log.Println(err)
  34. return
  35. }
  36. if resp.StatusCode() == 200 {
  37. body, err := resp.Body()
  38. if err != nil {
  39. log.Println(err)
  40. return
  41. }
  42. fmt.Println(string(body))
  43. }
  44. 或者打印Json
  45. if resp.StatusCode() == 200 {
  46. body, err := resp.Json()
  47. if err != nil {
  48. log.Println(err)
  49. return
  50. }
  51. fmt.Println(body)
  52. }
  53. }