From fb66b146bf2e7d842b7edac7a9b1a8fcec919158 Mon Sep 17 00:00:00 2001 From: Kushal Shukla Date: Fri, 10 Oct 2025 01:18:44 +0530 Subject: [PATCH] solution 5 --- .../kushalShukla-web/solution-template.go | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 challenge-5/submissions/kushalShukla-web/solution-template.go diff --git a/challenge-5/submissions/kushalShukla-web/solution-template.go b/challenge-5/submissions/kushalShukla-web/solution-template.go new file mode 100644 index 00000000..ad62e377 --- /dev/null +++ b/challenge-5/submissions/kushalShukla-web/solution-template.go @@ -0,0 +1,58 @@ +package main + +import ( + "fmt" + "net/http" +) + +const validToken = "secret" + +// AuthMiddleware checks the "X-Auth-Token" header. +// If it's "secret", call the next handler. +// Otherwise, respond with 401 Unauthorized. +func AuthMiddleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // TODO: Implement the logic: + // 1) Grab the "X-Auth-Token" header + // 2) Compare against validToken + // 3) If mismatch or missing, respond with 401 + // 4) Otherwise pass to next handler + authToken, exist := r.Header["X-Auth-Token"] + if !exist || authToken[0] != validToken { + http.Error(w, "", http.StatusUnauthorized) + return + } + next.ServeHTTP(w, r) + + }) +} + +// helloHandler returns "Hello!" on GET /hello +func helloHandler(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, "Hello!") +} + +// secureHandler returns "You are authorized!" on GET /secure +func secureHandler(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, "You are authorized!") +} + +// SetupServer configures the HTTP routes with the authentication middleware. +func SetupServer() http.Handler { + mux := http.NewServeMux() + + // Public route: /hello (no auth required) + mux.HandleFunc("/hello", helloHandler) + + // Secure route: /secure + // Wrap with AuthMiddleware + secureRoute := http.HandlerFunc(secureHandler) + mux.Handle("/secure", AuthMiddleware(secureRoute)) + + return mux +} + +func main() { + // Optional: you can run a real server for local testing + http.ListenAndServe(":8080", SetupServer()) +}