create a http server and read the request body as json in go

To create an HTTP server in Go and read the request body as JSON, follow these steps:

  1. Import the required packages: net/http and encoding/json
  2. Create a struct that matches the expected JSON data
  3. Parse the JSON request body into the created struct
  4. Start the HTTP server and handle incoming requests

Here is an example code snippet that implements the above steps:

main.go
package main

import (
    "net/http"
    "encoding/json"
)

type RequestBody struct {
    Name string `json:"name"`
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

func handler(w http.ResponseWriter, r *http.Request) {
    switch r.Method {
    case "POST":
        var reqBody RequestBody
        err := json.NewDecoder(r.Body).Decode(&reqBody)
        if err != nil {
            http.Error(w, err.Error(), http.StatusBadRequest)
            return
        }
        // Do something with the request body...
    default:
        http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
    }
}
649 chars
31 lines

In the above code, a HTTP server is started on port 8080. When a POST request is received, the request body is read and decoded into the RequestBody struct. The json struct tag is used to map the JSON property to the struct field. If there is an error decoding the JSON data, a 400 Bad Request response is returned. Otherwise, the request body can be used as needed.

related categories

gistlibby LogSnag