To create an HTTP server in Go and read the request body as JSON, follow these steps:
net/http
and encoding/json
Here is an example code snippet that implements the above steps:
main.go649 chars31 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.
gistlibby LogSnag