Ejemplo n.º 1
0
func ExampleToMiddleware() {
	// Let's convert a classic http middleware into a middleware supported by this package

	classicCORSMiddleware := func(next http.HandlerFunc) http.HandlerFunc {
		return func(rw http.ResponseWriter, r *http.Request) {
			// this middleware handles corss origin requests from browsers
			rw.Header().Set("Access-Control-Allow-Origin", "*")
			next.ServeHTTP(rw, r)
		}
	}

	convertedMiddleware := tiger.ToMiddleware(classicCORSMiddleware)

	// Let's test our converted middleware
	request, _ := http.NewRequest("GET", "https://acme.com", nil)
	response := httptest.NewRecorder()

	convertedMiddleware.
		Finish(func(c tiger.Container) { c.GetResponseWriter().Write([]byte("done")) }).
		Handle(&tiger.DefaultContainer{ResponseWriter: response, Request: request})

	fmt.Println(response.Header().Get("Access-Control-Allow-Origin"))
	fmt.Println(response.Body.String())

	// Output:
	// *
	// done

}
Ejemplo n.º 2
0
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()))
}