Skip to content

Instantly share code, notes, and snippets.

@aodin
Last active March 23, 2024 20:24
Show Gist options
  • Save aodin/9493190 to your computer and use it in GitHub Desktop.
Save aodin/9493190 to your computer and use it in GitHub Desktop.
Parsing JSON in a request body with Go
package main
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
)
type Message struct {
Id int64 `json:"id"`
Name string `json:"name"`
}
// curl localhost:8000 -d '{"name":"Hello"}'
func Cleaner(w http.ResponseWriter, r *http.Request) {
// Read body
b, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
http.Error(w, err.Error(), 500)
return
}
// Unmarshal
var msg Message
err = json.Unmarshal(b, &msg)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
output, err := json.Marshal(msg)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
w.Header().Set("content-type", "application/json")
w.Write(output)
}
func main() {
http.HandleFunc("/", Cleaner)
address := ":8000"
log.Println("Starting server on address", address)
err := http.ListenAndServe(address, nil)
if err != nil {
panic(err)
}
}
@Ammar022
Copy link

Nice work man. really appreciate it

@DaHogie
Copy link

DaHogie commented Nov 3, 2022

Thank you! Great discussion here everyone.

@aodin , thank you for the original post, and great writing for your response to handling the defer resp.Body.Close(). I found it to be enlightening in more ways that just an analysis of Go.

@ikrauchanka , thank you for noting to use decoder instead of unmarshal.

@tzachshabtay , thank you for being honest and sticking to your guns about your stance on the un-handled errors. Without that then there wouldn't have been as many chances to learn.

Have a great day peoples! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment