func main() { middle := interpose.New() router := mux.NewRouter() router.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, `<h1>Welcome to the public page!</h1><p><a href="/protected/">Rabbit hole</a></p>`) }) middle.UseHandler(router) // Now we will define a sub-router that uses the BasicAuth middleware // When you call any url starting with the path /protected, you will need to authenticate protectedRouter := mux.NewRouter().Methods("GET").PathPrefix("/protected").Subrouter() protectedRouter.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "Welcome to the protected page!") }) // Define middleware that pertains to the part of the site protected behind HTTP Auth // and add the protected router to the protected middleware protectedMiddlew := interpose.New() protectedMiddlew.Use(middleware.BasicAuth("john", "doe")) protectedMiddlew.UseHandler(protectedRouter) // Add the protected middleware and its router to the main router router.Methods("GET").PathPrefix("/protected").Handler(protectedMiddlew) http.ListenAndServe(":3001", middle) }
func main() { middle := interpose.New() router := mux.NewRouter() router.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, `<h1>Welcome to the public page!</h1><p><a href="/protected/">Rabbit hole</a></p>`) }) middle.UseHandler(router) // Now we will define a sub-router that uses the BasicAuth middleware // When you call any url starting with the path /protected, you will need to authenticate protectedRouter := mux.NewRouter().Methods("GET").PathPrefix("/protected").Subrouter() protectedRouter.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "Welcome to the protected page, %s!", context.Get(req, authKey)) }) protectedMiddlew := interpose.New() protectedMiddlew.Use(middleware.BasicAuthFunc(func(user, pass string, req *http.Request) bool { if middleware.SecureCompare(user, "admin") && middleware.SecureCompare(pass, "guessme") { context.Set(req, authKey, user) return true } else { return false } })) protectedMiddlew.Use(context.ClearHandler) protectedMiddlew.UseHandler(protectedRouter) router.Methods("GET").PathPrefix("/protected").Handler(protectedMiddlew) http.ListenAndServe(":3001", middle) }
func main() { middle := interpose.New() // First call middleware that may manipulate HTTP headers, since // they must be called before the HTTP body is manipulated // Using Gorilla framework's combined logger middle.Use(middleware.GorillaLog()) //Using Negroni's Gzip functionality middle.Use(middleware.NegroniGzip(gzip.DefaultCompression)) // Now call middleware that can manipulate the HTTP body // Define the router. Note that we can add the router to our // middleware stack before we define the routes, if we want. router := mux.NewRouter() middle.UseHandler(router) // Configure our router router.HandleFunc("/{user}", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "Welcome to the home page, %s!", mux.Vars(req)["user"]) }) // Define middleware that will apply to only some routes greenMiddle := interpose.New() // Tell the main router to send /green requests to our subrouter. // Again, we can do this before defining the full middleware stack. router.Methods("GET").PathPrefix("/green").Handler(greenMiddle) // Within the secondary middleware, just like above, we want to call anything that // will modify the HTTP headers before anything that will modify the body greenMiddle.UseHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("X-Favorite-Color", "green") })) // Finally, define a sub-router based on our love of the color green // When you call any url such as http://localhost:3001/green/man , you will // also see an HTTP header sent called X-Favorite-Color with value "green" greenRouter := mux.NewRouter().Methods("GET").PathPrefix("/green").Subrouter() //Headers("Accept", "application/json") greenMiddle.UseHandler(greenRouter) greenRouter.HandleFunc("/{user}", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "Welcome to the home page, green %s!", mux.Vars(req)["user"]) }) http.ListenAndServe(":3001", middle) }
func (a *AgentCommand) ServeHTTP() { r := mux.NewRouter().StrictSlash(true) a.apiRoutes(r) a.dashboardRoutes(r) middle := interpose.New() middle.Use(metaMiddleware(a.config.NodeName)) middle.UseHandler(r) r.Handle("/debug/vars", http.DefaultServeMux) r.PathPrefix("/dashboard").Handler( http.StripPrefix("/dashboard", http.FileServer( http.Dir(filepath.Join(a.config.UIDir, "static"))))) r.PathPrefix("/").Handler(http.RedirectHandler("/dashboard", 301)) srv := &http.Server{Addr: a.config.HTTPAddr, Handler: middle} log.WithFields(logrus.Fields{ "address": a.config.HTTPAddr, }).Info("api: Running HTTP server") certFile := "" //config.GetString("certFile") keyFile := "" //config.GetString("keyFile") if certFile != "" && keyFile != "" { go srv.ListenAndServeTLS(certFile, keyFile) } else { go srv.ListenAndServe() } }
func main() { middle := interpose.New() // Create a middleware that yields a global counter that increments until // the server is shut down. Note that this would actually require a mutex // or a channel to be safe for concurrent use. Therefore, this example is // unsafe. middle.Use(context.ClearHandler) middle.Use(func() func(http.Handler) http.Handler { c := 0 return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { c++ context.Set(req, CountKey, c) next.ServeHTTP(w, req) }) } }()) // Apply the router. router := mux.NewRouter() router.HandleFunc("/test/{user}", func(w http.ResponseWriter, req *http.Request) { c, ok := context.GetOk(req, CountKey) if !ok { fmt.Println("Context not ok") } fmt.Fprintf(w, "Hi %s, this is visit #%d to the site since the server was last rebooted.", mux.Vars(req)["user"], c) }) middle.UseHandler(router) http.ListenAndServe(":3001", middle) }
func main() { // middleware middle := interpose.New() middle.Use(adaptors.FromNegroni(cors.New(cors.Options{ // CORS AllowedOrigins: []string{"*"}, }))) // router router := pat.New() middle.UseHandler(router) router.Get("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { url := r.URL.Query().Get("url") if url != "" { encoded := imgbase64.FromRemote(url) fmt.Fprint(w, encoded) } else { fmt.Fprint(w, "/?url=<your-image-url> returns the base64 data-URI of that image.") } })) // listen port := os.Getenv("PORT") if port == "" { port = "5000" } log.Print("listening...") http.ListenAndServe(":"+port, middle) }
func main() { mw := interpose.New() // Set a random integer everytime someone loads the page mw.Use(context.ClearHandler) mw.Use(func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { c := rand.Int() fmt.Println("Setting ctx count to:", c) context.Set(req, CountKey, c) next.ServeHTTP(w, req) }) }) // Apply the router. router := mux.NewRouter() router.HandleFunc("/{user}", func(w http.ResponseWriter, req *http.Request) { c, ok := context.GetOk(req, CountKey) if !ok { fmt.Println("Get not ok") } fmt.Fprintf(w, "Welcome to the home page, %s!\nCount:%d", mux.Vars(req)["user"], c) }) mw.UseHandler(router) // Launch and permit graceful shutdown, allowing up to 10 seconds for existing // connections to end graceful.Run(":3001", 10*time.Second, mw) }
func main() { mw := interpose.New() // Turn on output buffering. It's added first because it encapsulates all other output. // This enables headers to be written after data is sent, because they're all stored // in a buffer, so the user's browser will see everything in the order it expects. mw.Use(middleware.Buffer()) // Tell the browser our output will be JSON. Note that because this is added // before the router, we will write JSON headers AFTER the router starts // writing output to the browser! Usually this would mean that the header would // not get set correctly. However, because we are buffering (see below), // nothing will get sent to the browser until all output is finished rendering. // This means that the header will get set correctly. mw.Use(func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { w.Header().Set("Content-Type", "application/json") next.ServeHTTP(w, req) }) }) // Apply the router. router := mux.NewRouter() router.HandleFunc("/{user}", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "Welcome to the home page, %s!", mux.Vars(req)["user"]) }) mw.UseHandler(router) // Launch and permit graceful shutdown, allowing up to 10 seconds for existing // connections to end graceful.Run(":3001", 10*time.Second, mw) }
func (a *AgentCommand) ServeHTTP() { r := mux.NewRouter().StrictSlash(true) a.apiRoutes(r) a.dashboardRoutes(r) middle := interpose.New() middle.UseHandler(r) // Path of static files must be last! r.PathPrefix("/").Handler(http.FileServer(http.Dir("static"))) srv := &http.Server{Addr: a.config.HTTPAddr, Handler: middle} log.Infof("Running HTTP server on %s", a.config.HTTPAddr) certFile := "" //config.GetString("certFile") keyFile := "" //config.GetString("keyFile") if certFile != "" && keyFile != "" { srv.ListenAndServeTLS(certFile, keyFile) } else { srv.ListenAndServe() } log.Debug("Exiting HTTP server") }
func main() { mw := interpose.New() // Use unrolled's secure framework // If you inspect the headers, you will see X-Frame-Options set to DENY // Must be called before the router because it modifies HTTP headers secureMiddleware := secure.New(secure.Options{ FrameDeny: true, }) mw.Use(secureMiddleware.Handler) // Apply the router. By adding it first, all of our other middleware will be // executed before the router, allowing us to modify headers before any // output has been generated. router := mux.NewRouter() mw.UseHandler(router) router.HandleFunc("/{user}", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "Welcome to the home page, %s!", mux.Vars(req)["user"]) }) // Launch and permit graceful shutdown, allowing up to 10 seconds for existing // connections to end graceful.Run(":3001", 10*time.Second, mw) }
func (me *endPoint) setupMuxHandlers(mux *mux.Router) { fn := handleIncoming(me) m := interpose.New() for i, _ := range me.modules { m.Use(me.modules[i]) //fmt.Println("using module:", me.modules[i], reflect.TypeOf(me.modules[i])) } m.UseHandler(http.HandlerFunc(fn)) if me.info.Version == "*" { mux.Handle(me.muxUrl, m).Methods(me.httpMethod) } else { urlWithVersion := cleanUrl(me.info.Prefix, "v"+me.info.Version, me.muxUrl) urlWithoutVersion := cleanUrl(me.info.Prefix, me.muxUrl) // versioned url mux.Handle(urlWithVersion, m).Methods(me.httpMethod) // content type (style1) header1 := fmt.Sprintf("application/%s-v%s+json", me.info.Vendor, me.info.Version) mux.Handle(urlWithoutVersion, m).Methods(me.httpMethod).Headers("Accept", header1) // content type (style2) header2 := fmt.Sprintf("application/%s+json;version=%s", me.info.Vendor, me.info.Version) mux.Handle(urlWithoutVersion, m).Methods(me.httpMethod).Headers("Accept", header2) } }
func main() { middle := interpose.New() // Tell the browser which server this came from. // This modifies headers, so we want this to be called before // any middleware which might modify the body (in HTTP, the headers cannot be // modified after the body is modified) middle.Use(func(next http.Handler) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("X-Server-Name", "Interpose Test Server") next.ServeHTTP(rw, req) }) }) // Apply the router. By adding it last, all of our other middleware will be // executed before the router, allowing us to modify headers before any // output has been generated. router := mux.NewRouter() middle.UseHandler(router) router.HandleFunc("/{user}", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "Welcome to the home page, %s!", mux.Vars(req)["user"]) }) // Launch and permit graceful shutdown, allowing up to 10 seconds for existing // connections to end graceful.Run(":3001", 10*time.Second, middle) }
func New() *WharfMaster { middle := interpose.New() // Logger middle.Use(middleware.GorillaLog()) // Header modification example middle.Use(func(next http.Handler) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("X-Server-Name", "The Germinator") next.ServeHTTP(rw, req) }) }) // Inject router router := mux.NewRouter() middle.UseHandler(router) // Setup Routes router.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) { fmt.Fprintf(rw, "Ther once was a happy roach, he liked to do roachy stuff") }) //router.HandleFunc("/v1/entities", ctrl.EntityCreate).Methods("POST") //router.HandleFunc("/v1/entities", ctrl.EntityList).Methods("GET") return &WharfMaster{Middle: middle} }
// TODO: use different middleware library ? func (app *Application) middlewares(cfg *libcfg.Cfg) (*interpose.Middleware, error) { middle := interpose.New() middle.Use(middlewares.Log()) middle.UseHandler(app.mux(cfg)) return middle, nil }
func main() { middle := interpose.New() // Send a header telling the world this is coming from an Interpose Test Server // You could imagine setting Content-type application/json or other useful // headers in other circumstances. middle.UseHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("X-Server-Name", "Interpose Test Server") })) // In this example, we use a basic router with a catchall route that // matches any path. In other examples in this project, we use a // more advanced router. // The last middleware added is the last executed, so by adding the router // last, our other middleware get a chance to modify HTTP headers before our // router writes to the HTTP Body router := http.NewServeMux() middle.UseHandler(router) router.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "Welcome to %s!", req.URL.Path) })) http.ListenAndServe(":3001", middle) }
func (chillax *Chillax) Middlewares() (*interpose.Middleware, error) { middle := interpose.New() middle.Use(middlewares.SetStorages(chillax.storages)) middle.UseHandler(chillax.Mux()) return middle, nil }
func (a *Application) middlewareStruct() (*interpose.Middleware, error) { mw := interpose.New() mw.Use(Nosurf()) mw.UseHandler(a.router()) return mw, nil }
func (app *Application) MiddlewareStruct() (*interpose.Middleware, error) { middle := interpose.New() middle.Use(middlewares.SetCookieStore(app.cookieStore)) middle.UseHandler(app.mux()) return middle, nil }
func Test_BasicAuthFunc(t *testing.T) { for auth, valid := range map[string]bool{ "foo:spam": true, "bar:spam": true, "foo:eggs": false, "bar:eggs": false, "baz:spam": false, "foo:spam:extra": false, "dummy:": false, "dummy": false, "": false, } { recorder := httptest.NewRecorder() encoded := "Basic " + base64.StdEncoding.EncodeToString([]byte(auth)) i := interpose.New() i.Use(BasicAuthFunc(func(username, password string, _ *http.Request) bool { return (username == "foo" || username == "bar") && password == "spam" })) i.Use(func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { w.Write([]byte("hello")) next.ServeHTTP(w, req) }) }) r, _ := http.NewRequest("GET", "foo", nil) i.ServeHTTP(recorder, r) if recorder.Code != 401 { t.Error("Response not 401, params:", auth) } if recorder.Body.String() == "hello" { t.Error("Auth block failed, params:", auth) } recorder = httptest.NewRecorder() r.Header.Set("Authorization", encoded) i.ServeHTTP(recorder, r) if valid && recorder.Code == 401 { t.Error("Response is 401, params:", auth) } if !valid && recorder.Code != 401 { t.Error("Response not 401, params:", auth) } if valid && recorder.Body.String() != "hello" { t.Error("Auth failed, got: ", recorder.Body.String(), "params:", auth) } if !valid && recorder.Body.String() == "hello" { t.Error("Auth block failed, params:", auth) } } }
func (app *Application) MiddlewareStruct() (*interpose.Middleware, error) { middle := interpose.New() middle.Use(middlewares.SetMcRouterConfigFile(app.Settings["MCROUTER_CONFIG_FILE"])) middle.Use(middlewares.SetStorage(app.Storage)) middle.Use(middlewares.SetReadOnly(app.IsReadOnly())) middle.UseHandler(app.mux()) return middle, nil }
func (app *Application) middlewareStruct(logWriter io.Writer) (*interpose.Middleware, error) { middle := interpose.New() middle.Use(middlewares.SetDB(app.db)) middle.Use(middlewares.SetCookieStore(app.cookieStore)) middle.Use(middlewares.SetupLogger(logWriter)) middle.UseHandler(app.mux()) return middle, nil }
func (app *Application) MiddlewareStruct() (*interpose.Middleware, error) { middle := interpose.New() middle.Use(middlewares.SetAddr(app.Addr)) middle.Use(middlewares.SetDB(app.db)) middle.Use(middlewares.SetCookieStore(app.cookieStore)) middle.Use(middlewares.SetWSTraffickers(app.WSTraffickers)) middle.UseHandler(app.mux()) return middle, nil }
func main() { // Limit to 5 requests globally. middle := interpose.New() middle.Use(throttler.Limit(2)) router := mux.NewRouter() router.HandleFunc("/", handler) middle.UseHandler(router) fmt.Printf("Try running the following commands (in different terminal):\n\n") fmt.Printf("for i in `seq 1 10`; do (curl 127.0.0.1:8000/ &); done\n\n") http.ListenAndServe(":8000", middle) }
func main() { middle := interpose.New() // Invoke the Gorilla framework's combined logger middle.Use(middleware.GorillaLog()) // Create a router to serve HTTP content at two paths // and tell our middleware about the router router := mux.NewRouter() middle.UseHandler(router) router.PathPrefix("/green").Subrouter().Handle("/{name}", Green(http.HandlerFunc(welcomeHandler))) router.Handle("/{name}", http.HandlerFunc(welcomeHandler)) http.ListenAndServe(":3001", middle) }
// BuildServer applies context-less middlewares. Ones with context will require some more work func BuildServer(middlewares []http.Handler, endpoints []Endpoint) http.Handler { handlerChain := interpose.New() for _, middle := range middlewares { handlerChain.UseHandler(middle) } router := mux.NewRouter() for _, endpoint := range endpoints { router.Methods(endpoint.GetMethod()). Path(endpoint.GetRoute()). HandlerFunc(endpoint.GetHandler().ServeHTTP) } handlerChain.UseHandler(router) return handlerChain }
func main() { model.Init() middle := interpose.New() middle.Use(middleware.NegroniGzip(gzip.DefaultCompression)) r := mux.NewRouter() middle.UseHandler(r) r.HandleFunc("/", page.ProfileHandler) r.HandleFunc("/profile", page.ProfileHandler) r.HandleFunc("/profile/{period}", page.ProfileHandler) r.HandleFunc("/badges", func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/progress", 302) }) r.HandleFunc("/progress", page.ProgressHandler) r.HandleFunc("/profiles", page.ProfilesHandler) r.HandleFunc("/admin/process", requireAdmin(page.ProcessIndexHandler)) r.HandleFunc("/admin/process/{owner}", requireAdmin(page.ProcessListHandler)) r.HandleFunc("/admin/process/{owner}/{faulty}/{previous}", requireAdmin(page.ProcessQueueHandler)) r.HandleFunc("/admin/process/{owner}/{faulty}/{previous}/run", requireAdmin(page.ProcessRunHandler)) r.HandleFunc("/signin", LoginHandler) r.HandleFunc("/logout", LogoutHandle) r.HandleFunc("/signup", page.SignupHandler).Methods("POST") r.HandleFunc("/reset_password/{token:[a-f0-9]+}", page.ResetPassViewHandler).Methods("GET") r.HandleFunc("/reset_password/{token:[a-f0-9]+}", page.ResetPassHandler).Methods("POST") r.HandleFunc("/reset_password", page.ResetPassMailHandler).Methods("POST") r.HandleFunc("/gplus", page.GPlusHandler) r.HandleFunc("/upload", page.UploadViewHandler).Methods("GET") r.HandleFunc("/upload", page.UploadHandler).Methods("POST") r.PathPrefix("/secret_cache/").Handler(http.StripPrefix("/secret_cache/", http.FileServer(http.Dir("cache")))) r.PathPrefix("/").Handler(http.FileServer(http.Dir("static"))) http.Handle("/", middle) go queue.ProcessQueue() queue.Queue <- true log.Fatal(http.ListenAndServeTLS(conf.Config.Address, conf.Config.Cert, conf.Config.Key, nil)) }
func main() { var err error db, err = neoism.Connect(os.Getenv("NEO4J_URL")) if err != nil { log.Fatal(err) } // middleware middle := interpose.New() middle.Use(adaptors.FromNegroni(cors.New(cors.Options{ // CORS AllowedOrigins: []string{"*"}, }))) // router router := mux.NewRouter() router.StrictSlash(true) // redirects '/path' to '/path/' middle.UseHandler(router) // ~ // > routes router.HandleFunc("/rel/", func(w http.ResponseWriter, r *http.Request) { handlers.CreateRelationship(db, w, r) }).Methods("POST") router.HandleFunc("/eql/", func(w http.ResponseWriter, r *http.Request) { handlers.CreateEquality(db, w, r) }).Methods("POST") router.HandleFunc("/btw/", func(w http.ResponseWriter, r *http.Request) { handlers.RelationshipsBetween(db, w, r) }).Methods("GET") router.HandleFunc("/cluster.svg", func(w http.ResponseWriter, r *http.Request) { handlers.ViewRelationships(db, w, r) }).Methods("GET") // ~ // static files router.PathPrefix("/").Handler(http.FileServer(http.Dir("./static/"))) // ~ port := os.Getenv("PORT") if port == "" { port = "5000" } log.Print("listening...") http.ListenAndServe(":"+port, middle) }
func main() { middle := interpose.New() // First apply any middleware that will not write output to http body // but which may (or may not) modify headers middle.Use(middleware.GorillaLog()) // Now apply any middleware that might modify the http body. This permits the // preceding middleware to alter headers router := mux.NewRouter() router.HandleFunc("/{user}", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "Welcome to the home page, %s!", mux.Vars(req)["user"]) }) middle.UseHandler(router) http.ListenAndServe(":3001", middle) }
func main() { router := mux.NewRouter() router.HandleFunc("/{user}", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "Welcome to the home page, %s!", mux.Vars(req)["user"]) }) middle := interpose.New() // Use Martini-Auth, a Martini library for basic HTTP authentication middle.Use(adaptors.FromMartini(auth.Basic("user", "basic"))) // Finally, add the router middle.UseHandler(router) // Now visit http://localhost:3001/guest and enter username "user" // and password "basic" http.ListenAndServe(":3001", middle) }
func main() { middle := interpose.New() // First apply any middleware that will not write output to http body // Log to stdout. Taken from Gorilla middle.Use(middleware.GorillaLog()) // Gzip output that follows. Taken from Negroni middle.Use(middleware.NegroniGzip(gzip.DefaultCompression)) // Now apply any middleware that modify the http body. router := mux.NewRouter() middle.UseHandler(router) router.HandleFunc("/{user}", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "Welcome to the home page, %s!", mux.Vars(req)["user"]) }) http.ListenAndServe(":3001", middle) }