func main() { goji.Get("/", IndexHandler) // Doesn't need CSRF protection (no POST/PUT/DELETE actions). signup := web.New() goji.Handle("/signup/*", signup) // But our signup forms do, so we add nosurf to their middleware stack (only). signup.Use(nosurf.NewPure) signup.Get("/signup/new", ShowSignupForm) signup.Post("/signup/submit", SubmitSignupForm) admin := web.New() // A more advanced example: we enforce secure cookies (HTTPS only), // set a domain and keep the expiry time low. a := nosurf.New(admin) a.SetBaseCookie(http.Cookie{ Name: "csrf_token", Domain: "localhost", Path: "/admin", MaxAge: 3600 * 4, HttpOnly: true, Secure: true, }) // Our /admin/* routes now have CSRF protection. goji.Handle("/admin/*", a) goji.Serve() }
func New() *web.Mux { mux := web.New() mux.Get("/api/logins", handler.GetLoginList) mux.Get("/api/stream/stdout/:id", handler.WsConsole) mux.Get("/api/stream/user", handler.WsUser) mux.Get("/api/auth/:host", handler.GetLogin) mux.Post("/api/auth/:host", handler.GetLogin) mux.Get("/api/badge/:host/:owner/:name/status.svg", handler.GetBadge) mux.Get("/api/badge/:host/:owner/:name/cc.xml", handler.GetCC) mux.Get("/api/hook/:host", handler.PostHook) mux.Put("/api/hook/:host", handler.PostHook) mux.Post("/api/hook/:host", handler.PostHook) repos := web.New() repos.Use(middleware.SetRepo) repos.Use(middleware.RequireRepoRead) repos.Use(middleware.RequireRepoAdmin) repos.Get("/api/repos/:host/:owner/:name/branches/:branch/commits/:commit/console", handler.GetOutput) repos.Get("/api/repos/:host/:owner/:name/branches/:branch/commits/:commit", handler.GetCommit) repos.Post("/api/repos/:host/:owner/:name/branches/:branch/commits/:commit", handler.PostCommit) repos.Get("/api/repos/:host/:owner/:name/commits", handler.GetCommitList) repos.Get("/api/repos/:host/:owner/:name", handler.GetRepo) repos.Put("/api/repos/:host/:owner/:name", handler.PutRepo) repos.Post("/api/repos/:host/:owner/:name", handler.PostRepo) repos.Delete("/api/repos/:host/:owner/:name", handler.DelRepo) mux.Handle("/api/repos/:host/:owner/:name*", repos) users := web.New() users.Use(middleware.RequireUserAdmin) users.Get("/api/users/:host/:login", handler.GetUser) users.Post("/api/users/:host/:login", handler.PostUser) users.Delete("/api/users/:host/:login", handler.DelUser) users.Get("/api/users", handler.GetUserList) mux.Handle("/api/users*", users) user := web.New() user.Use(middleware.RequireUser) user.Get("/api/user/feed", handler.GetUserFeed) user.Get("/api/user/repos", handler.GetUserRepos) user.Get("/api/user", handler.GetUserCurrent) user.Put("/api/user", handler.PutUser) mux.Handle("/api/user*", user) work := web.New() work.Use(middleware.RequireUserAdmin) work.Get("/api/work/started", handler.GetWorkStarted) work.Get("/api/work/pending", handler.GetWorkPending) work.Get("/api/work/assignments", handler.GetWorkAssigned) work.Get("/api/workers", handler.GetWorkers) work.Post("/api/workers", handler.PostWorker) work.Delete("/api/workers", handler.DelWorker) mux.Handle("/api/work*", work) return mux }
func main() { admin := web.New() admin.Use(middleware.SubRouter) admin.Post("/login", login) goji.Handle("/admin/*", admin) dashboard := web.New() dashboard.Use(auth) dashboard.Use(middleware.SubRouter) dashboard.Get("/json", sampleJsonHandle) goji.Handle("/dashboard/*", dashboard) goji.Use(middleware.Logger) goji.Serve() }
// Tests for failure if the middleware can't save to the Store. func TestStoreCannotSave(t *testing.T) { s := web.New() bs := &brokenSaveStore{} s.Use(Protect(testKey, setStore(bs))) s.Get("/", testHandler) r, err := http.NewRequest("GET", "/", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() s.ServeHTTP(rr, r) if rr.Code != http.StatusForbidden { t.Fatalf("broken store did not set an error status: got %v want %v", rr.Code, http.StatusForbidden) } if c := rr.Header().Get("Set-Cookie"); c != "" { t.Fatalf("broken store incorrectly set a cookie: got %v want %v", c, "") } }
func TestUserCreateError(t *testing.T) { count_before := 0 count_after := 0 m := web.New() rooter(m) ts := httptest.NewServer(m) defer ts.Close() db.Table("users").Count(&count_before) values := url.Values{} values.Add("Name", "エラー") req, _ := http.NewRequest("POST", ts.URL+"/user/new", strings.NewReader(values.Encode())) req.Header.Set("Authorization", "Basic dXNlcjp1c2Vy") req.Header.Add("Content-Type", "application/x-www-form-urlencoded") client := new(http.Client) response, _ := client.Do(req) db.Table("users").Count(&count_after) assert.Equal(t, 200, response.StatusCode) assert.Equal(t, count_before, count_after) }
func New() *web.Mux { mux := web.New() // Add routes to the global handler mux.Get("/api/badges/:name/:number/channel/:channel/sdk/:sdk/status.svg", handler.GetBadge) mux.Get("/api/badges/:name/:number/channel/:channel/status.svg", handler.GetBadge) mux.Get("/api/packages/:name/:number/channel/:channel/sdk/:sdk/stdout.txt", handler.GetOutput) mux.Get("/api/packages/:name/:number/channel/:channel/sdk/latest", handler.GetBuildLatest) mux.Get("/api/packages/:name/:number/channel/:channel/sdk/:sdk", handler.GetBuild) mux.Get("/api/channel/:channel", handler.GetChannel) mux.Get("/api/feed", handler.GetFeed) // Add routes for querying the build queue (workers) mux.Get("/api/work/started", handler.GetWorkStarted) mux.Get("/api/work/pending", handler.GetWorkPending) mux.Get("/api/work/assignments", handler.GetWorkAssigned) mux.Get("/api/workers", handler.GetWorkers) // Restricted operations mux.Delete("/sudo/api/workers/:id", handler.DelWorker) mux.Post("/sudo/api/workers", handler.PostWorker) mux.Post("/sudo/api/build", handler.PostBuild) // Main Pages mux.Get("/:name/:number/:channel/:sdk", handler.GetBuildPage) mux.Get("/:name/:number/:channel", handler.GetBuildPage) mux.Get("/", handler.GetHomePage) return mux }
func main() { // Initalize database. ExecuteSchemas() // Serve static files. staticDirs := []string{"bower_components", "res"} for _, d := range staticDirs { static := web.New() pattern, prefix := fmt.Sprintf("/%s/*", d), fmt.Sprintf("/%s/", d) static.Get(pattern, http.StripPrefix(prefix, http.FileServer(http.Dir(d)))) http.Handle(prefix, static) } goji.Use(applySessions) goji.Use(context.ClearHandler) goji.Get("/", handler(serveIndex)) goji.Get("/login", handler(serveLogin)) goji.Get("/github_callback", handler(serveGitHubCallback)) // TODO(samertm): Make this POST /user/email. goji.Post("/save_email", handler(serveSaveEmail)) goji.Post("/group/create", handler(serveGroupCreate)) goji.Post("/group/:group_id/refresh", handler(serveGroupRefresh)) goji.Get("/group/:group_id/join", handler(serveGroupJoin)) goji.Get("/group/:group_id", handler(serveGroup)) goji.Get("/group/:group_id/user/:user_id/stats.svg", handler(serveUserStatsSVG)) goji.Serve() }
func initRoutes() { // Setup static files static := web.New() static.Get("/static/*", http.StripPrefix("/static/", http.FileServer(http.Dir("./static/")))) http.Handle("/static/", static) // prepare routes, get/post stuff etc goji.Get("/", startPage) goji.Post("/held/action/:action/*", runActionAndRedirect) goji.Post("/held/complexaction", runComplexActionAndRedirect) goji.Post("/held/save", saveHeld) goji.Get("/held/isValid", isValid) // partial html stuff - sub-pages goji.Get("/held/page/new", pageNew) goji.Get("/held/page/modEigenschaften", pageModEigenschaften) goji.Get("/held/page/selectKampftechniken", pageSelectKampftechiken) goji.Get("/held/page/allgemeines", pageAllgemeines) goji.Get("/held/page/professionsAuswahl", pageAuswahlProfession) goji.Get("/held/page/kampftechniken", pageKampftechniken) goji.Get("/held/page/talente", pageTalente) goji.Get("/held/page/footer", pageFooter) goji.Get("/held/page/karmales", pageLiturgien) goji.Get("/held/page/magie", pageZauber) // json-accessors/ partial rest-API? goji.Get("/held/data/ap", getAP) }
func TestTemplateField(t *testing.T) { s := web.New() CSRF := Protect( testKey, FieldName(testFieldName), ) s.Use(CSRF) var token string var customTemplateField string s.Handle("/", web.HandlerFunc(func(c web.C, w http.ResponseWriter, r *http.Request) { token = Token(c, r) customTemplateField = string(TemplateField(c, r)) })) r, err := http.NewRequest("GET", "/", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() s.ServeHTTP(rr, r) expectedTemplateField := fmt.Sprintf(testTemplateField, testFieldName, token) if customTemplateField != expectedTemplateField { t.Fatalf("templateField not set correctly: got %v want %v", customTemplateField, expectedTemplateField) } }
// Test that our form helpers correctly inject a token into the response body. func TestFormToken(t *testing.T) { s := web.New() s.Use(Protect(testKey)) // Make the token available outside of the handler for comparison. var token string s.Get("/", web.HandlerFunc(func(c web.C, w http.ResponseWriter, r *http.Request) { token = Token(c, r) t := template.Must((template.New("base").Parse(testTemplate))) t.Execute(w, map[string]interface{}{ TemplateTag: TemplateField(c, r), }) })) r, err := http.NewRequest("GET", "/", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() s.ServeHTTP(rr, r) if rr.Code != http.StatusOK { t.Fatalf("middleware failed to pass to the next handler: got %v want %v", rr.Code, http.StatusOK) } if len(token) != base64.StdEncoding.EncodedLen(tokenLength*2) { t.Fatalf("token length invalid: got %v want %v", len(token), base64.StdEncoding.EncodedLen(tokenLength*2)) } if !strings.Contains(rr.Body.String(), token) { t.Fatalf("token not in response body: got %v want %v", rr.Body.String(), token) } }
func getServerInstance() *httptest.Server { api := NewApi() mux := web.New() api.Route(mux) return httptest.NewServer(mux) }
func main() { awsSession := session.New() awsSession.Config.WithRegion(os.Getenv("AWS_REGION")) tree = &dynamotree.Tree{ TableName: "hstore-example-shortlinks", DB: dynamodb.New(awsSession), } err := tree.CreateTable() if err != nil { log.Fatalf("hstore: %s", err) } goji.Get("/:link", ServeLink) goji.Post("/signup", CreateAccount) authMux := web.New() authMux.Use(RequireAccount) authMux.Post("/", CreateLink) authMux.Get("/", ListLinks) authMux.Delete("/:link", DeleteLink) // TODO(ross): this doesn't work (!) goji.Handle("/", authMux) goji.Serve() }
func NewRouter(b *backend.Backend) { router = Router{ Backend: b, } goji.Get("/ping", router.Ping) api := web.New() goji.Handle("/v1/*", api) api.Get("/overview", router.Overview) api.Get("/accounts", router.ShowAccount) api.Get("/accounts/:account_id", router.ShowAccount) api.Get("/categories", router.ShowCategory) api.Get("/categories/:category_id", router.ShowCategory) api.Post("/transaction", router.NewTransaction) api.Post("/account", router.NewAccount) api.Post("/category", router.NewCategory) api.Put("/transaction/:transaction_id", router.UpdateTransaction) api.Put("/account/:account_id", router.UpdateAccount) api.Put("/category/:category_id", router.UpdateCategory) api.Delete("/transaction/:transaction_id", router.DeleteTransaction) api.Delete("/account/:account_id", router.DeleteAccount) api.Delete("/category/:category_id", router.DeleteCategory) api.Use(goji.DefaultMux.Router) api.Use(middleware.SubRouter) }
func TestNewSession(t *testing.T) { store := sessions.NewCookieStore([]byte("secret")) fn := func(c web.C, w http.ResponseWriter, r *http.Request) { w.Write([]byte("ok")) } mux := web.New() mux.Handle("/*", fn) mux.Use(Middleware("session", store)) ts := httptest.NewServer(context.ClearHandler(mux)) defer ts.Close() var err error var resp *http.Response resp, err = http.Get(ts.URL) if err != nil { t.Fatal(err) } cookie := resp.Header.Get("Set-Cookie") t.Logf("Set-Cookie: %v", cookie) if cookie == "" { t.Fatal("\"Set-Cookie\" header missing") } matches := sessionPattern.FindStringSubmatch(cookie) if len(matches) != 2 { t.Fatal("session cookie missing") } }
func BenchmarkGoji_Middleware(b *testing.B) { middleware := func(h http.Handler) http.Handler { handler := func(w http.ResponseWriter, r *http.Request) { h.ServeHTTP(w, r) } return http.HandlerFunc(handler) } m := gojiweb.New() m.Get("/action", gojiHelloHandler) m.Use(middleware) m.Use(middleware) m.Use(middleware) m.Use(middleware) m.Use(middleware) m.Use(middleware) rw, req := testRequest("GET", "/action") b.ResetTimer() for i := 0; i < b.N; i++ { m.ServeHTTP(rw, req) if rw.Code != 200 { panic("goji: no good") } } }
func Start(conn *CGRConnector, user, pass string) { connector = conn username = user password = pass templates = template.Must(template.ParseGlob("templates/*.tmpl")) rpc.Register(conn) goji.Get(LOGIN_PATH, loginGet) goji.Post(LOGIN_PATH, loginPost) goji.Get("/app/*", http.FileServer(http.Dir("./static"))) auth := web.New() goji.Handle("/*", auth) auth.Use(SessionAuth) auth.Handle("/ws", websocket.Handler(func(ws *websocket.Conn) { jsonrpc.ServeConn(ws) })) auth.Post("/import/", importPost) auth.Post("/exportcdrs/", exportCdrsPost) auth.Post("/exporttpcsv/", exportTpToCsvPost) auth.Get("/accounts/logout", logoutGet) auth.Get("/", http.RedirectHandler("/app/", 301)) }
// SetupMainMux returns a goji Mux initialized with the middleware and a health check // handler. The mux is a net/http.Handler and thus has a ServeHTTP // method which can be convient to call in tests without the actual network stuff and // goroutine that SetupMainServer adds func SetupMainMux() *web.Mux { mx := web.New() gojiutil.AddCommon15(mx, log15.Root()) mx.Use(gojiutil.ParamsLogger(false)) // useful for debugging mx.Get("/health-check", healthCheckHandler) mx.NotFound(handleNotFound) return mx }
func init() { DefaultMux = web.New() DefaultMux.Use(middleware.RequestID) DefaultMux.Use(middleware.Logger) DefaultMux.Use(middleware.Recoverer) DefaultMux.Use(middleware.AutomaticOptions) }
func Include() { goji.Get("/", controllers.Home) goji.Get("/about", controllers.About) // Bookmarks app bookmarks := web.New() routes.Bookmarks(bookmarks) }
func Web() *web.Mux { mux := web.New() mux.Get("/people", frontend.ListPeople) mux.Get("/people/:person", frontend.GetPerson) return mux }
func main() { log.Println("Starting go-sig/web") if path := os.Getenv("IMG_PATH"); path != "" { imageRoot = path } log.Printf("Using image root: %s", imageRoot) if _, err := os.Stat(imageRoot); os.IsNotExist(err) { os.MkdirAll(imageRoot, 0750) } if procs := os.Getenv("PROCS"); procs != "" { if p, err := strconv.Atoi(procs); err != nil { runtime.GOMAXPROCS(p) } } if key := os.Getenv("AES_KEY"); key != "" { util.AES_KEY = []byte(key) } disableLogging := os.Getenv("DISABLE_LOGGING") if disableLogging == "1" || disableLogging == "true" { log.SetOutput(new(NullWriter)) } // Routes log.Println("Mapping routes...") goji.Get("/", index) // Setup static files static := web.New() static.Get("/assets/*", http.StripPrefix("/assets/", http.FileServer(http.Dir(publicPath)))) http.Handle("/assets/", static) profile := os.Getenv("ENABLE_DEBUG") if profile == "1" || profile == "true" { log.Println("Mapping debug routes...") goji.Handle("/debug/pprof/", pprof.Index) goji.Handle("/debug/pprof/cmdline", pprof.Cmdline) goji.Handle("/debug/pprof/profile", pprof.Profile) goji.Handle("/debug/pprof/symbol", pprof.Symbol) goji.Handle("/debug/pprof/block", pprof.Handler("block").ServeHTTP) goji.Handle("/debug/pprof/heap", pprof.Handler("heap").ServeHTTP) goji.Handle("/debug/pprof/goroutine", pprof.Handler("goroutine").ServeHTTP) goji.Handle("/debug/pprof/threadcreate", pprof.Handler("threadcreate").ServeHTTP) } // Generators log.Println("Registering generators...") registerGenerator(new(rs3.BoxGoalGenerator)) registerGenerator(new(multi.MultiGoalGenerator)) //registerGenerator(new(rs3.ExampleGenerator)) // Serve goji.Serve() }
func TestSubRouterMatch(t *testing.T) { m := web.New() m.Use(m.Router) m2 := web.New() m2.Use(SubRouter) m2.Get("/bar", func(w http.ResponseWriter, r *http.Request) {}) m.Get("/foo/*", m2) r, err := http.NewRequest("GET", "/foo/bar", nil) if err != nil { t.Fatal(err) } // This function will recurse forever if SubRouter + Match didn't work. m.ServeHTTP(httptest.NewRecorder(), r) }
func newMux() *web.Mux { mux := web.New() mux.Use(middleware.RequestID) mux.Use(server.Logger) mux.Use(middleware.Recoverer) mux.Use(middleware.AutomaticOptions) return mux }
func NewMux(webApp utils.WebApp) *web.Mux { mux := web.New() mux.Use(middleware.SubRouter) root := Root{WebApp: webApp} mux.Get("/", root.Index) return mux }
func Example() { m := web.New() // Use your favorite HTTP verbs and the interfaces you know and love // from net/http: m.Get("/hello", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Why hello there!\n") }) m.Post("/login", func(w http.ResponseWriter, r *http.Request) { if r.FormValue("password") != "god" { http.Error(w, "Hack the planet!", 401) } }) // Handlers can optionally take a context parameter, which contains // (among other things) a set of bound parameters. hello := func(c web.C, w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, %s!\n", c.URLParams["name"]) } // Bind parameters using pattern strings... m.Get("/hello/:name", hello) // ...or use regular expressions if you need additional power. bonjour := regexp.MustCompile(`^/bonjour/(?P<name>[A-Za-z]+)$`) m.Get(bonjour, hello) // Middleware are a great abstraction for performing logic on every // request. Some middleware use the Goji context object to set // request-scoped variables. logger := func(h http.Handler) http.Handler { wrap := func(w http.ResponseWriter, r *http.Request) { log.Println("Before request") h.ServeHTTP(w, r) log.Println("After request") } return http.HandlerFunc(wrap) } auth := func(c *web.C, h http.Handler) http.Handler { wrap := func(w http.ResponseWriter, r *http.Request) { if cookie, err := r.Cookie("user"); err == nil { c.Env["user"] = cookie.Value } h.ServeHTTP(w, r) } return http.HandlerFunc(wrap) } // A Middleware stack is a flexible way to assemble the common // components of your application, like request loggers and // authentication. There is an ecosystem of open-source middleware for // Goji, so there's a chance someone has already written the middleware // you are looking for! m.Use(middleware.EnvInit) m.Use(logger) m.Use(auth) }
// Test that we can extract a CSRF token from a multipart form. func TestMultipartFormToken(t *testing.T) { s := web.New() s.Use(Protect(testKey)) // Make the token available outside of the handler for comparison. var token string s.Handle("/", web.HandlerFunc(func(c web.C, w http.ResponseWriter, r *http.Request) { token = Token(c, r) t := template.Must((template.New("base").Parse(testTemplate))) t.Execute(w, map[string]interface{}{ TemplateTag: TemplateField(c, r), }) })) r, err := http.NewRequest("GET", "/", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() s.ServeHTTP(rr, r) // Set up our multipart form var b bytes.Buffer mp := multipart.NewWriter(&b) wr, err := mp.CreateFormField(fieldName) if err != nil { t.Fatal(err) } wr.Write([]byte(token)) mp.Close() r, err = http.NewRequest("POST", "/", &b) if err != nil { t.Fatal(err) } // Add the multipart header. r.Header.Set("Content-Type", mp.FormDataContentType()) // Send back the issued cookie. setCookie(rr, r) rr = httptest.NewRecorder() s.ServeHTTP(rr, r) if rr.Code != http.StatusOK { t.Fatalf("middleware failed to pass to the next handler: got %v want %v", rr.Code, http.StatusOK) } if body := rr.Body.String(); !strings.Contains(body, token) { t.Fatalf("token not in response body: got %v want %v", body, token) } }
func route(m *web.Mux) { resultMux := web.New() resultMux.Get("/face_detect/:name", http.StripPrefix("/face_detect/", http.FileServer(http.Dir("./results/")))) resultMux.Use(renameID) m.Handle("/face_detect/:name", resultMux) m.Get(toolURI, controllers.ControllPannel) m.Post(toolURI, controllers.RegisterFace) }
func API() *web.Mux { mux := web.New() mux.Get("/api/people", api.ListPeople) mux.Post("/api/people", api.CreatePerson) mux.Get("/api/people/:person", api.GetPerson) mux.Delete("/api/people/:person", api.DeletePerson) return mux }
func BenchmarkMultiGoji(b *testing.B) { g := web.New() g.Get("/hello/:name1/:name2/:name3/:name4", GojiMulti) responses, requests := generateMultiRequests(b) b.ResetTimer() for i := 0; i < b.N; i++ { g.ServeHTTP(responses[i], requests[i]) } }
func testServer(route, output string) *httptest.Server { mux := http.NewServeMux() server := httptest.NewServer(mux) m := web.New() m.Post(route, func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, output) }) mux.Handle("/", m) return server }