发布时间:2024-11-05 17:19:02
client := &http.Client{}
client.Timeout = time.Second * 10
req, err := http.NewRequest("GET", "http://example.com", nil)
req.Header.Set("Authorization", "Bearer xxxxxxx")
data := url.Values{}
data.Set("key1", "value1")
data.Set("key2", "value2")
req, err := http.NewRequest("POST", "http://example.com", strings.NewReader(data.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := client.Do(req)
statusCode := resp.StatusCode
headers := resp.Header
body, err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
type User struct {
ID int
Name string
}
var user User
err := json.NewDecoder(resp.Body).Decode(&user)
if err != nil {
log.Fatal(err)
}
if resp.StatusCode == http.StatusOK {
// 处理成功响应
} else {
// 处理失败响应
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second * 10)
defer cancel()
req = req.WithContext(ctx)
resp, err = client.Do(req)