Skip to content

Commit 03fe116

Browse files
Return error response as json
1 parent 3539b07 commit 03fe116

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

header_auth.go

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package headerauthentication
22

33
import (
44
"context"
5+
"encoding/json"
56
"fmt"
67
"net/http"
78
)
@@ -11,6 +12,11 @@ type Config struct {
1112
Header map[string]string `json:"header,omitempty"`
1213
}
1314

15+
// ErrorResponse represents the response when the API key is invalid .
16+
type ErrorResponse struct {
17+
ErrorCode string `json:"error_code"`
18+
}
19+
1420
// CreateConfig creates the default plugin configuration.
1521
func CreateConfig() *Config {
1622
return &Config{
@@ -38,14 +44,15 @@ func New(ctx context.Context, next http.Handler, config *Config, name string) (h
3844
}
3945

4046
func (a *HeaderAuth) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
41-
fmt.Println("a.header " + a.header["name"])
4247
if req.Header.Get(a.header["name"]) == a.header["key"] {
43-
fmt.Println("SUCCESS")
4448
req.Header.Del(a.header["name"])
4549
a.next.ServeHTTP(rw, req)
4650
return
4751
}
48-
fmt.Println("FAILED")
49-
http.Error(rw, "Not allowed - verified null", http.StatusUnauthorized)
50-
52+
response := ErrorResponse{ErrorCode: "Invalid API Key"}
53+
rw.Header().Set("Content-Type", "application/json; charset=utf-8")
54+
rw.WriteHeader(403)
55+
if err := json.NewEncoder(rw).Encode(response); err != nil {
56+
fmt.Println("Failed to reply request with invalid API Key: " + err.Error())
57+
}
5158
}

0 commit comments

Comments
 (0)