This repository has been archived by the owner on Jan 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
example_test.go
45 lines (40 loc) · 1.61 KB
/
example_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package connectauth_test
import (
"context"
"fmt"
"net/http"
"connectrpc.com/connect"
"go.akshayshah.org/connectauth"
)
// Our authentication logic is just a function.
func authenticate(ctx context.Context, req *connectauth.Request) (any, error) {
const passphrase = "open-sesame"
if req.Header.Get("Authorization") != "Bearer "+passphrase {
// If authentication fails, we return an error. connectauth.Errorf is a
// convenient shortcut to produce an error coded with
// connect.CodeUnauthenticated.
return nil, connectauth.Errorf("try %q as a bearer token instead", passphrase)
}
// Once we've authenticated the request, we can return some information about
// the client. That information gets attached to the context passed to
// subsequent interceptors and our service implementation.
return "Ali Baba", nil
}
// This constructor would normally be generated by protoc-gen-connect-go. For
// this example, we'll use a small stub.
func NewHelloServiceHandler(svc any, opts ...connect.HandlerOption) (string, http.Handler) {
return "/hello.v1/Hello", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Service implementations can retrieve information about the authenticated
// caller from the context.
identity := connectauth.GetInfo(r.Context())
fmt.Fprintf(w, "Hello, %v!", identity)
})
}
func Example() {
mux := http.NewServeMux()
mux.Handle(NewHelloServiceHandler(struct{}{}))
// Before starting the HTTP server, wrap the whole mux in our authenticating
// middleware.
middleware := connectauth.NewMiddleware(authenticate)
http.ListenAndServe("localhost:8080", middleware.Wrap(mux))
}