# Go Cheatsheet - Send HTTP Request

## HTTP Request

### GET

#### Simple GET Request

```go
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`

```go
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

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

#### POST Request with FormValue

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

#### POST with Client Object

```go
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)
```




