Basic authentication implementation for Go.
go get github.com/nanoninja/bulma
After installing Go and setting up your
GOPATH, create your first .go
file.
package main
import (
"fmt"
"net/http"
"github.com/nanoninja/bulma"
)
func main() {
onSuccess := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Dashboard")
})
ba := bulma.BasicAuth(bulma.Realm, onSuccess, bulma.User{
"foo": "bar",
"bar": "foo",
})
http.Handle("/admin", ba)
http.ListenAndServe(":3000", nil)
}
func main() {
onSuccess := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Dashboard")
})
validator := bulma.ValidateFunc(func(c *bulma.Credential) bool {
return c.Authorization && c.Username == "foo" && c.Password == "bar"
})
ba := bulma.BasicAuth(bulma.Realm, onSuccess, validator)
http.Handle("/admin", ba)
http.ListenAndServe(":3000", nil)
}
The configuration allows you to set up HTTP authentication.
type Config struct {
Realm string
Validator Validator
Success http.Handler
Error http.Handler
}
Example :
func main() {
onSuccess := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Dashboard")
})
onError := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "My Custom Error Handler")
})
ba := bulma.New(&bulma.Config{
Realm: "MyRealm",
Validator: bulma.Auth("foo", "bar"),
Success: onSuccess,
Error: onError,
})
http.Handle("/admin", ba)
http.ListenAndServe(":3000", nil)
}
To create a validator, use bulma.Validator interface.
type Validator interface {
Validate(*Credential) bool
}
Example :
type MyValidator struct {
username, password string
}
func (v MyValidator) Validate(c *bulma.Credential) bool {
return c.Authorization && v.username == c.Username && v.password == c.Password
}
Using your own validator
func main() {
onSuccess := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Dashboard")
})
ba := bulma.BasicAuth("MyRealm", onSuccess, MyValidator{"foo", "bar"})
http.Handle("/admin", ba)
http.ListenAndServe(":3000", nil)
}
Bulma is licensed under the Creative Commons Attribution 3.0 License, and code is licensed under a BSD license.