簡單的GET請求
func Test1() {
resp, err := http.Get("http://localhost:8080/test")
if err != nil {
log.Fatal(err)
}
body, _ := ioutil.ReadAll(resp.Body)
var data interface{}
json.Unmarshal(body, &data)
fmt.Println(data)
}
帶引數的GET請求
func Test2() {
req, err := http.NewRequest("GET", "http://localhost:8080/test", nil)
if err != nil {
log.Fatal(err)
}
params := req.URL.Query()
params.Add("action", "get")
params.Add("page", "2")
req.URL.RawQuery = params.Encode()
resp, _ := http.DefaultClient.Do(req)
body, _ := ioutil.ReadAll(resp.Body)
var data interface{}
json.Unmarshal(body, &data)
fmt.Println(data)
}
設定超時時間的GET請求
func Test3() {
req, err := http.NewRequest("GET", "http://localhost:8080/test", nil)
if err != nil {
log.Fatal(err)
}
var t int64 = 5
ctx, _ := context.WithTimeout(context.Background(), time.Duration(t) * time.Second)
params := req.URL.Query()
params.Add("action", "get")
params.Add("page", "2")
req.URL.RawQuery = params.Encode()
resp, _ := http.DefaultClient.Do(req.WithContext(ctx))
body, _ := ioutil.ReadAll(resp.Body)
var data interface{}
json.Unmarshal(body, &data)
fmt.Println(data)
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結