Beispiel #1
0
func ExampleServer_errorHandling() {
	// Custom error handling:
	//
	// Every Router can have its own error handler. In this example
	// a custom error handler is set on the API sub router to handler
	// all errors occured on the /api route.
	//
	// Note: it is also possible to overwrite the default error handler of
	// the server.
	server := goserv.NewServer()

	server.Get("/error", func(w http.ResponseWriter, r *http.Request) {
		err := fmt.Errorf("a server error")
		goserv.Context(r).Error(err, http.StatusInternalServerError)
	})

	api := server.SubRouter("/api")
	api.Get("/error", func(w http.ResponseWriter, r *http.Request) {
		err := fmt.Errorf("a API error")
		goserv.Context(r).Error(err, http.StatusInternalServerError)
	})

	// Handle errors occured on the API router.
	api.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err *goserv.ContextError) {
		log.Printf("API Error: %s", err)

		w.WriteHeader(err.Code)
		goserv.WriteString(w, err.String())
	}

	log.Fatalln(server.Listen(":12345"))
}
Beispiel #2
0
func ExampleServer_context() {
	// Share data between handlers:
	//
	// The middleware stores a shared value in the RequestContext under the name "shared".
	// The GET handler is the next handler in line and retrieves the value from the
	// context. Since a RequestContext can store arbitrary types a type assertion
	// is necessary to get the value in it's real type.
	server := goserv.NewServer()

	server.Use(func(w http.ResponseWriter, r *http.Request) {
		goserv.Context(r).Set("shared", "something to share")
	})

	server.Get("/", func(w http.ResponseWriter, r *http.Request) {
		shared := goserv.Context(r).Get("shared").(string)
		goserv.WriteString(w, shared)
	})

	log.Fatalln(server.Listen(":12345"))
}
Beispiel #3
0
func ExampleServer_simple() {
	// A simple server example.
	//
	// First an access logging function is registered which gets invoked
	// before the request is forwarded to the home handler. After that
	// the home handler is registered which is the final handler writing
	// a simple message to the response body.
	//
	// As a last step server.Listen is called to start listening for incoming
	// requests.
	server := goserv.NewServer()

	server.Use(func(w http.ResponseWriter, r *http.Request) {
		log.Printf("Access %s %s", r.Method, r.URL.String())
	}).Get("/", func(w http.ResponseWriter, r *http.Request) {
		goserv.WriteString(w, "Welcome Home")
	})

	log.Fatalln(server.Listen(":12345"))
}