Skip to content

Instantly share code, notes, and snippets.

@ian-kent
Created May 17, 2017 20:10
Show Gist options
  • Save ian-kent/ae95d5d5cd1d0e3f3b2d260340b2a754 to your computer and use it in GitHub Desktop.
Save ian-kent/ae95d5d5cd1d0e3f3b2d260340b2a754 to your computer and use it in GitHub Desktop.
json unmarshal
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/gorilla/mux"
)
type input struct {
Foo string `json:"foo"`
}
func main() {
r := mux.NewRouter()
r.Methods("GET").Path("/").HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
var i input
if !getJSON(w, req, &i) {
return
}
fmt.Printf("%+v\n", i)
})
if err := http.ListenAndServe(":9876", r); err != nil {
panic(err)
}
}
func getJSON(w http.ResponseWriter, req *http.Request, i interface{}) bool {
b, err := ioutil.ReadAll(req.Body)
if err != nil {
w.WriteHeader(400)
return false
}
defer req.Body.Close()
err = json.Unmarshal(b, &i)
if err != nil {
w.WriteHeader(400)
return false
}
return true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment