NewAuthenticatedHandler is an example of middleware that works with both RPC and non-RPC clients.
(handler http.Handler)
| 34 | // NewAuthenticatedHandler is an example of middleware that works with both RPC |
| 35 | // and non-RPC clients. |
| 36 | func 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 | |
| 59 | func ExampleErrorWriter() { |
| 60 | mux := http.NewServeMux() |
no test coverage detected