go语言中curl的使用
go get -v -u github.com/wujiangweiphp/go-curl
/**
* 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("请求失败")
}
}
}
/**
* 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("请求失败")
}
}
}
百度地图根据经纬度查询省市区信息
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