Exemplo n.º 1
0
// DefaultFormat returns a middleware that logs http requests
// to the given logger using the default log format.
func DefaultFormat(l *log.Logger) httpmux.MiddlewareFunc {
	return func(next http.HandlerFunc) http.HandlerFunc {
		return func(w http.ResponseWriter, r *http.Request) {
			start := time.Now()
			rw := NewResponseWriter(w)
			next(rw, r)
			b := getBuffer()
			b.WriteString(r.Proto)
			b.Write([]byte(" "))
			b.WriteString(strconv.Itoa(rw.Code()))
			b.Write([]byte(" "))
			b.WriteString(r.Method)
			b.Write([]byte(" "))
			b.WriteString(r.URL.RequestURI())
			b.Write([]byte(" from "))
			b.WriteString(r.RemoteAddr)
			b.Write([]byte(" "))
			fmt.Fprintf(b, "%q", r.Header.Get("User-Agent"))
			b.Write([]byte(" "))
			b.WriteString(strconv.Itoa(rw.Bytes()))
			b.Write([]byte(" bytes in "))
			b.WriteString(time.Since(start).String())
			if err := httpmux.Context(r).Value(ErrorID); err != nil {
				fmt.Fprintf(b, " err: %v", err)
			}
			l.Print(b.String())
			putBuffer(b)
		}
	}
}
Exemplo n.º 2
0
func TestErrorln(t *testing.T) {
	var ctx context.Context
	mux := httpmux.New()
	mux.GET("/", func(w http.ResponseWriter, r *http.Request) {
		Errorln(r, "hello", "world")
		ctx = httpmux.Context(r)
	})
	r := &http.Request{Method: "GET", URL: &url.URL{Path: "/"}}
	mux.ServeHTTP(&httptest.ResponseRecorder{}, r)
	if ctx.Value(ErrorID) != "hello world\n" {
		t.Fatalf("Unexpected value. Want \"hello world\\n\", have %v", ctx.Value("error"))
	}
}
Exemplo n.º 3
0
func authHandler(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		u, p, ok := r.BasicAuth()
		if ok && u == "foobar" && p == "foobared" {
			ctx := httpmux.Context(r)
			ctx = context.WithValue(ctx, "user", u)
			httpmux.SetContext(ctx, r)
			next(w, r)
			return
		}
		w.Header().Set("WWW-Authenticate", `realm="restricted"`)
		w.WriteHeader(http.StatusUnauthorized)
	}
}
Exemplo n.º 4
0
func Example() {
	// curl -i localhost:8080
	// curl -i -XPOST --basic -u foobar:foobared localhost:8080/auth/login
	root := httpmux.New()
	root.GET("/", func(w http.ResponseWriter, r *http.Request) {
		io.WriteString(w, "hello, world\n")
	})
	auth := httpmux.New()
	{
		auth.UseFunc(authHandler)
		auth.POST("/login", func(w http.ResponseWriter, r *http.Request) {
			u := httpmux.Context(r).Value("user")
			fmt.Fprintln(w, "hello,", u)
		})
	}
	root.Append("/auth", auth)
	http.ListenAndServe(":8080", root)
}
Exemplo n.º 5
0
// Errorln associates message v with the request context.
func Errorln(r *http.Request, v ...interface{}) {
	ctx := httpmux.Context(r)
	ctx = context.WithValue(ctx, ErrorID, fmt.Sprintln(v...))
	httpmux.SetContext(ctx, r)
}
Exemplo n.º 6
0
// Errorf associates message v with the request context.
func Errorf(r *http.Request, format string, v ...interface{}) {
	ctx := httpmux.Context(r)
	ctx = context.WithValue(ctx, ErrorID, fmt.Sprintf(format, v...))
	httpmux.SetContext(ctx, r)
}