Skip to content

Instantly share code, notes, and snippets.

@primayudantra
Forked from aodin/gist:9493190
Created October 17, 2017 12:44
Show Gist options
  • Save primayudantra/52cd9306349b1bd3543dc90eb976ff94 to your computer and use it in GitHub Desktop.
Save primayudantra/52cd9306349b1bd3543dc90eb976ff94 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