MCPcopy
hub / github.com/connectrpc/connect-go / NewAuthenticatedHandler

Function NewAuthenticatedHandler

error_writer_example_test.go:36–57  ·  view source on GitHub ↗

NewAuthenticatedHandler is an example of middleware that works with both RPC and non-RPC clients.

(handler http.Handler)

Source from the content-addressed store, hash-verified

34// NewAuthenticatedHandler is an example of middleware that works with both RPC
35// and non-RPC clients.
36func NewAuthenticatedHandler(handler http.Handler) http.Handler {
37 errorWriter := connect.NewErrorWriter()
38 return http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
39 // Dummy authentication logic.
40 if request.Header.Get("Token") == "super-secret" {
41 handler.ServeHTTP(response, request)
42 return
43 }
44 defer request.Body.Close()
45 defer io.Copy(io.Discard, request.Body)
46 if errorWriter.IsSupported(request) {
47 // Send a protocol-appropriate error to RPC clients, so that they receive
48 // the right code, message, and any metadata or error details.
49 unauthenticated := connect.NewError(connect.CodeUnauthenticated, errors.New("invalid token"))
50 errorWriter.Write(response, request, unauthenticated)
51 } else {
52 // Send an error to non-RPC clients.
53 response.WriteHeader(http.StatusUnauthorized)
54 io.WriteString(response, "invalid token")
55 }
56 })
57}
58
59func ExampleErrorWriter() {
60 mux := http.NewServeMux()

Callers 1

ExampleErrorWriterFunction · 0.85

Calls 8

IsSupportedMethod · 0.95
WriteMethod · 0.95
NewErrorWriterFunction · 0.92
NewErrorFunction · 0.92
ServeHTTPMethod · 0.80
GetMethod · 0.65
CloseMethod · 0.65
WriteHeaderMethod · 0.45

Tested by

no test coverage detected