0xBF
0xBF

0xBF

Go Cheatsheet - Send HTTP Request

0xBF's photo
0xBF

Published on Apr 23, 2021

1 min read

HTTP Request

GET

Simple GET Request

url := "http://ip-api.com/json/129.49.234.203"
resp, err := http.Get(url)

Use Client to Send GET

Use http.Client is the most flexible way to send http request:

  1. Build a Client object
  2. Build a Request object, then we can add headers, cookie, form values to this request
  3. Use the client object to send this request using client.Do
client := http.Client{
    Timeout: 5 * time.Second,
}
request, err := http.NewRequest("GET", url, nil)
if err != nil {
    log.Fatalln("Failed to build request", err)
}
request.Header.Add("X-API-Key", "test-api-key")
cookie := &http.Cookie{Name: "userId", Value: "12345")}
request.AddCookie(cookie)
resp, err = client.Do(request)

POST

Simple POST Request

resp, err := http.Post(
    "http://localhost:8080/login.do",
    "application/x-www-form-urlencoded",
    strings.NewReader("mobile=xxxxxxxxxx&isRemberPwd=1"),
)

POST Request with FormValue

postParam := url.Values{}
postParam.Add("keyword", "golang")
postParam.Add("lang", "en")
resp, err = http.PostForm("https://api.com", postParam)

POST with Client Object

client := http.Client{
    Timeout: 5 * time.Second,
}
request, err := http.NewRequest("POST", url, nil)
if err != nil {
    log.Fatalln("Failed to build request", err)
}
request.PostForm.Add("lang", "en")
request.Header.Add("X-API-Key", "test-api-key")
cookie := &http.Cookie{Name: "userId", Value: "12345")}
request.AddCookie(cookie)
resp, err = client.Do(request)
 
Share this