Go Language
Go Language

HTTP Requests returning JSON in Go Language


This is a useful function for sending HTTP requests to API’s that return JSON. You can view a full example on Go Playground, but this script will not run on go playground because they do not allow TCP requests. You can copy the script into your environment for it to run.

Getting a String from JSON Response

1
2
response := HttpJsonResponse("http://swapi.co/api/people/1", "GET", nil)
fmt.Println("Name: ", response["name"].(string))

Sending Parameters with POST Request

1
2
3
4
5
6
7
postInput := map[string]string{
		"title": "Post Title",
		"body": "New post added in body",
		"userId": "66",
	}
	postResponse := HttpJsonResponse("http://jsonplaceholder.typicode.com/posts", "POST", postInput)
	fmt.Println("New Post ID: ", postResponse["id"].(float64))

HttpJsonResponse Function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//import (
//	"net/http"
//	"io/ioutil"
//	"encoding/json"
//	"fmt"
//)
func HttpJsonResponse(url string, method string, params map[string]string) map[string]interface{} {
	req, err := http.NewRequest(method, url, nil)
	q := req.URL.Query()
	for k, v := range params {
		q.Add(k, v)
	}
	req.URL.RawQuery = q.Encode()
	client := &http.Client{}
	var jsonResponse map[string]interface{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	json.Unmarshal(body, &jsonResponse)
	return jsonResponse
}

View Comments
There are currently no comments.