Skip to content

Instantly share code, notes, and snippets.

@lantins
Last active August 29, 2015 14:12
Show Gist options
  • Save lantins/9d35e2d63b262116d2ee to your computer and use it in GitHub Desktop.
Save lantins/9d35e2d63b262116d2ee to your computer and use it in GitHub Desktop.
Golang - HTTP Server - Contexts
package main
import (
"fmt"
"github.com/julienschmidt/httprouter"
"log"
"net/http"
"os"
"strconv"
)
type appContext struct {
someBool bool
params *httprouter.Params
session *sessionContext
}
type sessionContext struct {
userID int64
}
type appHandle func(http.ResponseWriter, *http.Request, *appContext) (int, error)
func RouteWithContext(c *appContext, handle appHandle) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
log.Println("AppHandler anon func")
c.params = &p
c.session = &sessionContext{}
c.session.userID = 5
status, err := handle(w, r, c)
if err != nil {
log.Printf("HTTP %d: %q", status, err)
http.Error(w, http.StatusText(status), status)
return
}
}
}
func NewAppContext() *appContext {
return &appContext{someBool: true}
}
func main() {
// log to stdout (the default is stderr).
log.SetOutput(os.Stdout)
log.Println("*** running")
context := NewAppContext()
// wire routes to handlers
router := httprouter.New()
router.GET("/", RouteWithContext(context, IndexHandler))
router.GET("/set/:id", RouteWithContext(context, SetHandler))
// listen and serve
err := http.ListenAndServe(":8080", router)
if err != nil {
log.Fatal(err)
}
}
func IndexHandler(w http.ResponseWriter, r *http.Request, c *appContext) (int, error) {
log.Println("IndexHandler")
fmt.Fprintln(w, "IndexHandler")
fmt.Fprintf(w, " - userID = %d\n", c.session.userID)
fmt.Fprintf(w, " - someBool = %t\n", c.someBool)
return 200, nil
}
func SetHandler(w http.ResponseWriter, r *http.Request, c *appContext) (int, error) {
log.Println("SetHandler")
id, err := strconv.ParseInt(c.params.ByName("id"), 10, 0)
if err != nil {
return 500, err
}
c.session.userID = id
http.Redirect(w, r, "/", http.StatusSeeOther)
return http.StatusSeeOther, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment