Initial commit: wb-mock skeleton
This commit is contained in:
33
internal/middleware/auth.go
Normal file
33
internal/middleware/auth.go
Normal file
@ -0,0 +1,33 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func Auth(expectedAPIKey string, next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
apiKey := r.Header.Get("Authorization")
|
||||
|
||||
if apiKey == "" {
|
||||
writeError(w, 401, "missing credentials: Authorization header is required")
|
||||
return
|
||||
}
|
||||
|
||||
if expectedAPIKey != "" && apiKey != expectedAPIKey {
|
||||
writeError(w, 403, "invalid api key")
|
||||
return
|
||||
}
|
||||
|
||||
next(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func writeError(w http.ResponseWriter, code int, msg string) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(code)
|
||||
json.NewEncoder(w).Encode(map[string]any{
|
||||
"code": code,
|
||||
"message": msg,
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user