Skip to content

Instantly share code, notes, and snippets.

@carlozamagni
Forked from aodin/gist:9493190
Created November 1, 2018 14:18
Show Gist options
  • Save carlozamagni/b1e9b0d94415f84e3aa40e9f642cb542 to your computer and use it in GitHub Desktop.
Save carlozamagni/b1e9b0d94415f84e3aa40e9f642cb542 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)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment