Created
May 17, 2017 20:10
-
-
Save ian-kent/ae95d5d5cd1d0e3f3b2d260340b2a754 to your computer and use it in GitHub Desktop.
json unmarshal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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