Golang http request demo code.

net/http

To send a http request, easily use "net/http" module.

GET Method

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
func httpGet(uri string) string {
	response, err := http.Get(uri)
	if err != nil {
		log.Fatal(err)
	}
	
	defer response.Body.Close()
	bodyBytes, err := ioutil.ReadAll(response.Body)
	if err != nil {
		log.Fatal(err)
	}
	return string(bodyBytes)
}

or use:

1
2
3
4
5
...
client := http.Client{}
request, _ := http.NewRequest("GET", "https://postman-echo.com/get?foo1=bar1&foo2=bar2", nil)
response, _ := client.Do(request)
...

POST Method

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
func httpPost(uri string) string {
	reader := strings.NewReader(url.Values{
		"foo1": {"bar1"},
		"foo2": {"bar2"},
	}.Encode())
	
	response, err := http.Post(uri, "application/x-www-form-urlencoded", reader)
	if err != nil {
		log.Fatal(err)
	}
	bodyBytes, _ := ioutil.ReadAll(response.Body)
	return string(bodyBytes)
}

or use:

1
2
3
4
5
6
...
client := http.Client{}
request, _ := http.NewRequest("POST", "https://postman-echo.com/post", reader)
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
response, _ := client.Do(request)
...

if you want to send Content-Type: application/json request:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
func httpPostJson(uri string) string {
	var jsonStr = []byte(`
		{
			"foo1":"bar1",
			"foo2":"bar2",
		}
	`)

	response, err := http.Post(uri, "application/json", bytes.NewBuffer(jsonStr))
	if err != nil {
		log.Fatal(err)
	}
	defer response.Body.Close()
	bodyBytes, _ := ioutil.ReadAll(response.Body)
	return string(bodyBytes)
}

GoRequest

GoRequest – Simplified HTTP client ( inspired by famous SuperAgent lib in Node.js )
With GoRequest things become easier.

GET Method

1
2
3
4
5
request := gorequest.New()
resp, body, err := request.Get("https://postman-echo.com/get?foo1=bar1&foo2=bar2").End()
if err != nil {
    log.Fatal(err)
}