func main() { // tiger support dependency injection like Martini // it is completely optional. // All is needed is to wrap the default container into // a container that has an injector provider // then wrap handlers with tiger.Inject router := tiger.NewRouter() router.Use(func(c tiger.Container, next tiger.Handler) { container := &tiger.ContainerWithInjector{Container: c} container.GetInjector().SetLogger(&logger.DefaultLogger{}) // let's register a few services for demonstration purposes container.GetInjector().RegisterValue(&DB{"mysql://localhost"}) container.GetInjector().MustRegisterFactory(func(w http.ResponseWriter) (*json.Encoder, error) { return json.NewEncoder(w), nil }) container.GetInjector().MustRegisterFactory(func(r *http.Request) (url.Values, error) { return r.URL.Query(), nil }) // we need to pass the wrapped container to the next handlers next(container) }) router.Post("/user/:name", tiger.Inject(func(db *DB, encoder *json.Encoder, w http.ResponseWriter, query url.Values) { id, err := db.Execute("INSERT INTO TABLE FOO(name) values(?)", query.Get(":name")) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.WriteHeader(http.StatusCreated) encoder.Encode(map[string]interface{}{"Status": "Created", "ID": id}) })) addr := ":8080" log.Printf("Listening on %s", addr) log.Fatal(http.ListenAndServe(addr, router.Compile())) }
func main() { addr := "127.0.0.1:8080" // Create a router router := tiger.NewRouter() // Use a tiger.Handler to read url variables router.Get("/greetings/:name", func(container tiger.Container) { name := container.GetRequest().URL.Query().Get(":name") fmt.Fprintf(container.GetResponseWriter(), "Hello %s ! ", name) }) // Use an idiomatic http.Handlerfunc as the app index router.Get("/", tiger.FromHandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, ` <html> <body> <h3>Index</h3> <p>Welcome to tiger ! <p><a href="/secure">Login</a> </body> </html> `) })) // Compile and use with http.Server log.Printf("Listening on %s \n", addr) log.Fatal(http.ListenAndServe(addr, router.Compile())) }
func ExampleRouter_Sub() { // Router.Sub allows router inheritance // SubRouters can be created to allow a custom middleware queue // executed by "sub" handlers router := app.NewRouter() router. Use(func(c app.Container, next app.Handler) { c.GetResponseWriter().Header().Set("X-Root", "Yes") next(c) }). Sub("/sub/"). Use(func(c app.Container, next app.Handler) { // Will only get executed by by handlers defined // in that sub router c.GetResponseWriter().Header().Set("X-Sub", "Yes") next(c) }). Get("/", func(c app.Container) { fmt.Fprint(c.GetResponseWriter(), "Sub") }) response := httptest.NewRecorder() request, _ := http.NewRequest("GET", "http://example.com/sub/", nil) router.Compile().ServeHTTP(response, request) fmt.Println(response.Header().Get("X-Root")) fmt.Println(response.Header().Get("X-Sub")) // Output: // Yes // Yes }
func main() { addr := "127.0.0.1:8080" // Create a router router := tiger.NewRouter() // Use an idiomatic http middleware to log requests router.Use(tiger.ToMiddleware(func(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { next(w, r) log.Printf("%s %s", r.Method, r.URL.RequestURI()) } })) // Use an idiomatic http.Handlerfunc as the app index router.Get("/", tiger.FromHandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, ` <html> <body> <h3>Index</h3> <p>Welcome to tiger ! <p><a href="/secure">Login</a> </body> </html> `) })) // Use a tiger.Handler to read url variables router.Get("/greetings/:name", func(container tiger.Container) { name := container.GetRequest().URL.Query().Get(":name") fmt.Fprintf(container.GetResponseWriter(), "Hello %s ! ", name) }) // Create a subrouter secureRouter := router.Sub("/secure") // Basic security middleware that will be executed // on each request matching that subroute secureRouter.Use(func(c tiger.Container, next tiger.Handler) { // use the default implementation of tiger.Container injected in the router by default if login, password, ok := c.GetRequest().BasicAuth(); ok { if login == "login" && password == "password" { next(c) return } } // or return a 401 status code c.GetResponseWriter().Header().Set("WWW-Authenticate", `Basic realm="Secure"`) c.Error(tiger.StatusError(http.StatusUnauthorized), http.StatusUnauthorized) }) secureRouter.Get("/", func(c tiger.Container) { fmt.Fprintf(c.GetResponseWriter(), `<body> <p>You are in the secure zone ! congrats!</p> </body>`) }) // Compile and use with http.Server log.Printf("Listening on %s \n", addr) log.Fatal(http.ListenAndServe(addr, router.Compile())) }
func ExampleRouter_Mount() { // Mount allows to define modules // That can be reused in different application. // NewTestModule returns a *TestModule // that has a method with the following signature: // // func(module TestModule)Connect(collection *app.RouteCollection) // router := app.NewRouter() router.Mount("/mount", NewTestModule()) response := httptest.NewRecorder() request, _ := http.NewRequest("GET", "http://example.com/mount", nil) router.Compile().ServeHTTP(response, request) fmt.Println("Status", response.Code) // Output: // Status 200 }
func ExampleRouter() { router := app.NewRouter() router.Use(func(container app.Container, next app.Handler) { container.GetResponseWriter().Header().Add("X-Special", "Yes") next(container) }) router.Get("/greetings/:firstname/:lastname", func(container app.Container) { fmt.Fprintf(container.GetResponseWriter(), "Hello %s %s !", container.GetRequest().URL.Query().Get(":firstname"), container.GetRequest().URL.Query().Get(":lastname"), ) }) response := httptest.NewRecorder() request, _ := http.NewRequest("GET", "http://example.com/greetings/John-Rodger/Doe", nil) router.Compile().ServeHTTP(response, request) fmt.Println(response.Body.String()) fmt.Println(response.Header().Get("X-Special")) // Output: // Hello John-Rodger Doe ! // Yes }