Skip to content

Instantly share code, notes, and snippets.

@digitalcraftsman
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save digitalcraftsman/7319a71f187acd6fe379 to your computer and use it in GitHub Desktop.
Save digitalcraftsman/7319a71f187acd6fe379 to your computer and use it in GitHub Desktop.
Goji - adding routes based on a map
package main
import (
"encoding/json"
"net/http"
"github.com/zenazn/goji"
"github.com/zenazn/goji/web"
)
var routes []Route
func init() {
routes = []Route{
Route{"Get", goji.Get, "/index", hello},
Route{"Get", goji.Get, "/sitemap", sitemap},
}
}
type Route struct {
Method string `json:"method"`
add func(web.PatternType, web.HandlerType) `json:"-"`
Pattern string `json:"pattern"`
Handler web.HandlerType `json:"-"`
}
var methods = map[string]func(web.PatternType, web.HandlerType){
"Get": goji.Get,
"Post": goji.Post,
"PATCH": goji.Patch,
"PUT": goji.Put,
"Delete": goji.Delete,
}
func (r Route) Add() {
r.add(r.Pattern, r.Handler)
}
func hello(c web.C, w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello world"))
}
func sitemap(c web.C, w http.ResponseWriter, r *http.Request) {
resp, err := json.MarshalIndent(routes, "", " ")
if err != nil {
http.Error(w, "Can't generate the response properly.", 500)
}
w.Write(resp)
}
func main() {
for _, r := range routes {
r.Add()
}
goji.Serve()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment