Пример #1
0
func init() {
	DefaultMux = web.New()

	DefaultMux.Use(middleware.RequestID)
	DefaultMux.Use(middleware.Logger)
	DefaultMux.Use(middleware.Recoverer)
	DefaultMux.Use(middleware.AutomaticOptions)
}
Пример #2
0
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)
}
Пример #3
0
func main() {
	// Add routes to the global handler
	goji.Get("/", Root)
	// Fully backwards compatible with net/http's Handlers
	goji.Get("/greets", http.RedirectHandler("/", 301))
	// Use your favorite HTTP verbs
	goji.Post("/greets", NewGreet)
	// Use Sinatra-style patterns in your URLs
	goji.Get("/users/:name", GetUser)
	// Goji also supports regular expressions with named capture groups.
	goji.Get(regexp.MustCompile(`^/greets/(?P<id>\d+)$`), GetGreet)

	// Middleware can be used to inject behavior into your app. The
	// middleware for this application are defined in middleware.go, but you
	// can put them wherever you like.
	goji.Use(PlainText)

	// If the patterns ends with "/*", the path is treated as a prefix, and
	// can be used to implement sub-routes.
	admin := web.New()
	goji.Handle("/admin/*", admin)

	// The standard SubRouter middleware helps make writing sub-routers
	// easy. Ordinarily, Goji does not manipulate the request's URL.Path,
	// meaning you'd have to repeat "/admin/" in each of the following
	// routes. This middleware allows you to cut down on the repetition by
	// eliminating the shared, already-matched prefix.
	admin.Use(middleware.SubRouter)
	// You can also easily attach extra middleware to sub-routers that are
	// not present on the parent router. This one, for instance, presents a
	// password prompt to users of the admin endpoints.
	admin.Use(SuperSecure)

	admin.Get("/", AdminRoot)
	admin.Get("/finances", AdminFinances)

	// Goji's routing, like Sinatra's, is exact: no effort is made to
	// normalize trailing slashes.
	goji.Get("/admin", http.RedirectHandler("/admin/", 301))

	// Use a custom 404 handler
	goji.NotFound(NotFound)

	// Sometimes requests take a long time.
	goji.Get("/waitforit", WaitForIt)

	// Call Serve() at the bottom of your main() function, and it'll take
	// care of everything else for you, including binding to a socket (with
	// automatic support for systemd and Einhorn) and supporting graceful
	// shutdown on SIGINT. Serve() is appropriate for both development and
	// production.
	goji.Serve()
}
Пример #4
0
func TestNoCache(t *testing.T) {

	rr := httptest.NewRecorder()
	s := web.New()

	s.Use(NoCache)
	r, err := http.NewRequest("GET", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	s.ServeHTTP(rr, r)

	for k, v := range noCacheHeaders {
		if rr.HeaderMap[k][0] != v {
			t.Errorf("%s header not set by middleware.", k)
		}
	}
}