Skip to content

Instantly share code, notes, and snippets.

@codegangsta
Created July 7, 2015 23:08

Revisions

  1. codegangsta created this gist Jul 7, 2015.
    64 changes: 64 additions & 0 deletions main.go
    Original 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)
    }
    }