Handling Errors

Rafał Lorenz edited this page Feb 23, 2018 · 4 revisions
  1. Recover Middleware

Recover Middleware

package main

import (
	"fmt"
	"log"
	"net/http"

        "github.com/vardius/gorouter"
)

func recover(next http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			if rcv := recover(); rcv != nil {
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			}
		}()

		next.ServeHTTP(w, r)
	}

	return http.HandlerFunc(fn)
}

func Index(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "Ok!\n")
}

func WithError(w http.ResponseWriter, r *http.Request) {
	panic("panic recover")
}

func main() {
	router := gorouter.New(recoverfunc)
	router.GET("/", http.HandlerFunc(Index))
	router.GET("/panic", http.HandlerFunc(WithError))

	log.Fatal(http.ListenAndServe(":8080", router))
}
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.