Golang http request demo code.

net/http

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

GET Method

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:

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

POST Method

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:

...
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:

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

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