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