Created
July 7, 2015 23:08
-
-
Save codegangsta/3f9d1852385dc29935bf to your computer and use it in GitHub Desktop.
JSON and Middleware
This file contains 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" | |
"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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment