以 map[string]interface{}
传参调用
func post(api string, params map[string]interface{}) string {
var values []string
for k, v := range params {
switch v.(type) {
case string:
values = append(values, fmt.Sprintf("%s=%s", k, v))
case int:
values = append(values, fmt.Sprintf("%s=%d", k, v))
default:
continue
}
}
resp, err := http.Post(api, "application/x-www-form-urlencoded", strings.NewReader(strings.Join(values, "&")))
if err != nil || resp.StatusCode != 200 {
fmt.Println(err.Error())
return ""
}
contentBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(err.Error())
return ""
}
return string(contentBytes)
}
json格式post
func postJSON(url string, params map[string]interface{}) string {
data, err := json.Marshal(params)
if err != nil {
fmt.Println(err.Error())
return ""
}
req, err := http.NewRequest("POST", url, bytes.NewReader(data))
if err != nil {
fmt.Println(err.Error())
return ""
}
req.Header.Set("Content-Type", "application/json")
client := http.Client{}
resp, err := client.Do(req)
if err != nil || resp.StatusCode != 200 {
fmt.Println(err.Error())
return ""
}
respBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(err.Error())
return ""
}
return string(respBytes)
}
有疑问加站长微信联系(非本文作者)