mirror of
https://github.com/therootcompany/golib.git
synced 2026-03-02 23:57:59 +00:00
docs+fix: add RequestAuthenticator godoc example; use 10_000 numeric literal
Co-authored-by: coolaj86 <122831+coolaj86@users.noreply.github.com>
This commit is contained in:
parent
9e7a50b443
commit
7465f584d9
35
auth/request_example_test.go
Normal file
35
auth/request_example_test.go
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
package auth_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/therootcompany/golib/auth"
|
||||||
|
)
|
||||||
|
|
||||||
|
// exampleCreds is a toy BasicAuthenticator used only in the example below.
|
||||||
|
type exampleCreds struct{}
|
||||||
|
|
||||||
|
func (exampleCreds) Authenticate(username, password string) (auth.BasicPrinciple, error) {
|
||||||
|
return nil, fmt.Errorf("not implemented")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ExampleRequestAuthenticator shows the typical usage pattern.
|
||||||
|
// Build a RequestAuthenticator once (at startup), attach your credential
|
||||||
|
// store as the Authenticator, then call Authenticate in each handler.
|
||||||
|
// Call Challenge before writing a 401 so the browser knows which scheme
|
||||||
|
// to offer.
|
||||||
|
func ExampleRequestAuthenticator() {
|
||||||
|
ra := auth.NewRequestAuthenticator()
|
||||||
|
ra.Authenticator = exampleCreds{} // swap in your real credential store
|
||||||
|
|
||||||
|
http.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
principle, err := ra.Authenticate(r)
|
||||||
|
if err != nil {
|
||||||
|
ra.Challenge(w) // sets WWW-Authenticate: Basic
|
||||||
|
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, "hello %s", principle.ID())
|
||||||
|
})
|
||||||
|
}
|
||||||
@ -186,7 +186,7 @@ func parseSinceLimit(r *http.Request) (time.Time, int) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
limit := 10000
|
limit := 10_000
|
||||||
if l := r.URL.Query().Get("limit"); l != "" {
|
if l := r.URL.Query().Get("limit"); l != "" {
|
||||||
if n, err := strconv.Atoi(strings.ReplaceAll(l, "_", "")); err == nil && n > 0 {
|
if n, err := strconv.Atoi(strings.ReplaceAll(l, "_", "")); err == nil && n > 0 {
|
||||||
limit = n
|
limit = n
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user