Skip to content

clevergo/middleware

Repository files navigation

Middleware Build Status Coverage Status Go Report Card GoDoc Release

A collection of HTTP middlewares.

Middlewares

Example

package main

import (
	"compress/gzip"
	"fmt"
	"log"
	"net/http"
	"os"

	"github.com/clevergo/clevergo"
	"github.com/clevergo/middleware"
	"github.com/gorilla/handlers"
)

var users = map[string]string{
	"foo": "bar",
}

var basicAuthValidate = func(username, password string) bool {
	if passwd, exists := users[username]; exists && passwd == password {
		return true
	}
	return false
}

var basicAuthErrorHandler http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	http.Error(w, "invalid credential", http.StatusUnauthorized)
})

func main() {
	app := clevergo.New(":1234")
	app.Use(
		handlers.RecoveryHandler(),
		middleware.Compress(gzip.DefaultCompression),
		middleware.Logging(os.Stdout),
	)
	app.Get("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, "hello world")
	})

	// basic auth
	basicAuth := middleware.BasicAuth(
		basicAuthValidate,
		middleware.BasicAuthRealm("Restricted"),                 // optional.
		middleware.BasicAuthErrorHandler(basicAuthErrorHandler), // optional.
	)
	auth := app.Group("/auth", clevergo.RouteGroupMiddleware(basicAuth))
	auth.Get("/", func(w http.ResponseWriter, r *http.Request) {
		user := middleware.GetBasicAuthUser(r)
		fmt.Fprintf(w, "hello %s", user)
	})

	log.Fatal(app.ListenAndServe())
}
$ curl -v http://localhost:1234/auth/
...
< HTTP/1.1 401 Unauthorized
< Www-Authenticate: Basic realm="Restricted"
invalid credential

$ curl -v -u foo:bar http://localhost:1234/auth/
...
> Authorization: Basic Zm9vOmJhcg==
...
< Www-Authenticate: Basic realm="Restricted"
hello foo

About

A collection of HTTP middlewares for golang

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages