概览

在 golang 程序中进行 http 请求时,一般的步骤是:

  • 组合 url 和 param 参数
  • get 和 put 需要准备请求体数据
  • 进行 http 请求(设置超时)
  • 错误判断和状态码判断
  • http 返回内容解析

如果后端程序每个 http 请求都如上面这样处理,将产生很多相似的代码,

并且在复制代码的时候,容易出错(需要修改的地方忘记修改),浪费 debug 的时间。

于是,我封装了一个简便的 httputil 库,用于 http 请求。

详见 https://github.com/chinaran/httputil

  • 支持 get, post, put, patch, delete 方法
  • 支持 string, []byte, map, struct 作为 request 和 response 数据
  • 默认超时:30s
  • 默认传输类型:application/json

示例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package main

import (
	"context"
	"log"

	hu "github.com/chinaran/httputil"
)

func main() {
	// get
	urlGet := "https://httpbin.org/get?hello=world"
	respGetM := map[string]interface{}{}
	if err := hu.Get(context.TODO(), urlGet, &respGetM, hu.WithLogTimeCost()); err != nil {
		log.Printf("Get %s err: %s", urlGet, err)
		return
	}
	log.Printf("Get %s map response: %+v", urlGet, respGetM)
	respGetStr := ""
	if err := hu.Get(context.TODO(), urlGet, &respGetStr, hu.WithLogTimeCost()); err != nil {
		log.Printf("Get %s err: %s", urlGet, err)
		return
	}
	log.Printf("Get %s string response: %+v", urlGet, respGetStr)

	// post
	urlPost := "https://httpbin.org/post"
	req := map[string]string{"hello": "world"}
	respPost := struct {
		Data string `json:"data"`
	}{}
	if err := hu.Post(context.TODO(), urlPost, &req, &respPost, hu.WithLogTimeCost()); err != nil {
		log.Printf("Post %s err: %s", urlPost, err)
		return
	}
	log.Printf("Post %s struct response: %+v", urlPost, respPost)
}

示例结果

示例结果