Skip to content

Instantly share code, notes, and snippets.

@codegangsta
Created July 7, 2015 23:08
Show Gist options
  • Save codegangsta/3f9d1852385dc29935bf to your computer and use it in GitHub Desktop.
Save codegangsta/3f9d1852385dc29935bf to your computer and use it in GitHub Desktop.
JSON and Middleware
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: "jeremy@codegangsta.io",
}
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