|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | +"fmt" |
| 5 | +"net/http" |
| 6 | +) |
| 7 | + |
| 8 | +const validToken = "secret" |
| 9 | + |
| 10 | +// AuthMiddleware checks the "X-Auth-Token" header. |
| 11 | +// If it's "secret", call the next handler. |
| 12 | +// Otherwise, respond with 401 Unauthorized. |
| 13 | +func AuthMiddleware(next http.Handler) http.Handler { |
| 14 | +return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 15 | +// TODO: Implement the logic: |
| 16 | +// 1) Grab the "X-Auth-Token" header |
| 17 | +// 2) Compare against validToken |
| 18 | +// 3) If mismatch or missing, respond with 401 |
| 19 | +// 4) Otherwise pass to next handler |
| 20 | + |
| 21 | +token := r.Header.Get("X-Auth-Token") |
| 22 | +if token != validToken { |
| 23 | +http.Error(w, "", 401) |
| 24 | +return |
| 25 | +} |
| 26 | +next.ServeHTTP(w, r) |
| 27 | +}) |
| 28 | +} |
| 29 | + |
| 30 | +// helloHandler returns "Hello!" on GET /hello |
| 31 | +func helloHandler(w http.ResponseWriter, r *http.Request) { |
| 32 | +if r.Method != http.MethodGet { |
| 33 | +http.Error(w, "xd", 401) |
| 34 | +return |
| 35 | +} |
| 36 | +fmt.Fprint(w, "Hello!") |
| 37 | +} |
| 38 | + |
| 39 | +// secureHandler returns "You are authorized!" on GET /secure |
| 40 | +func secureHandler(w http.ResponseWriter, r *http.Request) { |
| 41 | +fmt.Fprint(w, "You are authorized!") |
| 42 | +} |
| 43 | + |
| 44 | +// SetupServer configures the HTTP routes with the authentication middleware. |
| 45 | +func SetupServer() http.Handler { |
| 46 | +mux := http.NewServeMux() |
| 47 | + |
| 48 | +// Public route: /hello (no auth required) |
| 49 | +mux.HandleFunc("/hello", helloHandler) |
| 50 | + |
| 51 | +// Secure route: /secure |
| 52 | +// Wrap with AuthMiddleware |
| 53 | +secureRoute := http.HandlerFunc(secureHandler) |
| 54 | +mux.Handle("/secure", AuthMiddleware(secureRoute)) |
| 55 | + |
| 56 | +return mux |
| 57 | +} |
| 58 | + |
| 59 | +func main() { |
| 60 | +// Optional: you can run a real server for local testing |
| 61 | +// http.ListenAndServe(":8080", SetupServer()) |
| 62 | +} |
0 commit comments