Parse JSON from POST request in GoLang

We will be using the “net/http” package to retrive a POST request and parse its data.

First of all let’s create a go file, call it main.go.

In it, under the Main function, add the following code to serve the application on localhost:3000:8080, and also add the HandleFunc code which will handle any incoming requests to the URL localhost/3000:8080/create endpoint. We don’t have a createhandler function yet, but we will create one.

	http.HandleFunc("/create", createhandler)
	log.Fatal(http.ListenAndServe(":8080", nil))

Now create a new function called createhandler

func createhandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Access-Control-Allow-Credentials", "true")
	w.Header().Set("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT")
	w.Header().Set("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers")
	fmt.Println("we got a POST req")
	body := map[string]interface{}{}
	json.NewDecoder(r.Body).Decode(&body)
	fmt.Println(body["title"])
}

First of all, this is a testing application so I will just open up the server for any incoming requests from any domain so that there is no errors for CORS (Cross-Origin Resource Sharing). I will also set the content type to JSON with application/json, and utf8 encoding. I’ll also allow any method such as GET HEAD OPTIONS POST PUT. Now that’s done, let’s take a look at the interesting things.

To parse a POST request in golang we will first define a variable called body which is of the type map with an empty interface, then we will use the json package to call on the method NewDecoder, where we put in the incoming request body (r.Body), and then decode it into the body variable. Then we can simply play with the map values like body[“title”], assuming your JSON data contains a title field.

To pass data to play with, you could use axios in a javascript/typescript environment like this:

function SendData() {
    axios.post("http://localhost:8080/create",
      { title: "hellooo my title.."}
      ).then((response: any) => {
          // done..
    });
}
0 0 votes
Article rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments