go语言中常用的功能之五(CURL)

go语言中curl的使用

1. 使用条件

1.1 下载依赖包curl

go get -v -u github.com/wujiangweiphp/go-curl

1.2 go使用curl发起get请求

/**
 *  get请求
 *  @param url string  请求地址
 *  @param queries map[string]string 请求参数
 *  @return string,error
 */
func HttpGet(url string, queries map[string]string) (string,error) {
	headers := map[string]string{
		"Content-Type":  "application/json",
	}
	req := curl.NewRequest()
	resp, err := req.
		SetUrl(url).
		SetHeaders(headers).
		SetQueries(queries).
		Get()
	if err != nil {
		return "" ,err
	} else {
		if resp.IsOk() {
			return resp.Body,nil
		} else {
			log.Printf("%v\n",resp.Raw)
			return "" ,errors.New("请求失败")
		}
	}
}

1.3 go使用curl发起post请求

/**
 *  get请求
 *  @param url string  请求地址
 *  @param queries map[string]string 请求参数
 *  @return string,error
 */
func HttpPost(url string, queries map[string]string,postData map[string]interface{}) (string,error) {
	headers := map[string]string{
		//"User-Agent":    "Sublime",
		//"Authorization": "Bearer access_token",
		"Content-Type":  "application/json",
	}

	cookies := map[string]string{
		//"userId":    "12",
		//"loginTime": "15045682199",
	}

	// 链式操作
	req := curl.NewRequest()
	resp, err := req.
		SetUrl(url).
		SetHeaders(headers).
		SetCookies(cookies).
		SetQueries(queries).
		SetPostData(postData).
		Post()

	if err != nil {
		return "" ,err
	} else {
		if resp.IsOk() {
			return resp.Body,nil
		} else {
			log.Printf("%v\n",resp.Raw)
			return "" ,errors.New("请求失败")
		}
	}
}

2. 使用实例

百度地图根据经纬度查询省市区信息

url := "https://api.map.baidu.com/geocoder"
queries := map[string]string{
	"location": "30.187588,120.19237",
	"output":  "json",
}
res ,err := HttpGet(url,queries)
if err != nil {
	fmt.Println(err)
	return
}

var address interface{}
err = json.Unmarshal([]byte(res),&address)
if err != nil {
	fmt.Println(err)
	return
}

ad := address.(map[string]interface{})
result := ad["result"].(map[string]interface{})
component := result["addressComponent"].(map[string]interface{})

fmt.Println(ad)
fmt.Println(ad["status"]) //OK
fmt.Println(result["formatted_address"]) //浙江省杭州市滨江区滨康路469号
fmt.Println(component["city"]) //杭州市

参考github地址:https://github.com/mikemintang/go-curl

猜你喜欢

转载自blog.csdn.net/wujiangwei567/article/details/86596561