Created
July 7, 2015 23:08
Revisions
-
codegangsta created this gist
Jul 7, 2015 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,64 @@ package main import ( "encoding/json" "net/http" "github.com/codegangsta/negroni" "github.com/julienschmidt/httprouter" ) type Book struct { Title string Author string } type User struct { Name string Email string } func main() { n := negroni.Classic() mux := httprouter.New() mux.GET("/users", Users) mux.GET("/books", Books) n.UseFunc(Auth) n.UseHandler(mux) n.Run(":8080") } func Users(rw http.ResponseWriter, r *http.Request, p httprouter.Params) { user := User{ Name: "Jeremy", Email: "[email protected]", } json.NewEncoder(rw).Encode(user) } func Books(rw http.ResponseWriter, r *http.Request, p httprouter.Params) { book := Book{ Title: "Building Web apps in Go", Author: "Jeremy", } data, err := json.Marshal(book) if err != nil { http.Error(rw, err.Error(), 500) return } rw.Header().Set("Content-Type", "application/json") rw.Write(data) } func Auth(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) { if r.URL.Query().Get("password") == "secret123" { next(rw, r) } else { http.Error(rw, "Not Authorized", 401) } }