Skip to content

Commit 58c2e60

Browse files
Add solution for Challenge 5 (#838)
Co-authored-by: go-interview-practice-bot[bot] <230190823+go-interview-practice-bot[bot]@users.noreply.github.com>
1 parent 0e7f10d commit 58c2e60

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
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+
tokenReceived := r.Header.Get("X-Auth-Token")
18+
// 2) Compare against validToken
19+
if len(tokenReceived) > 0 && tokenReceived == validToken {
20+
// 4) Otherwise pass to next handler
21+
w.WriteHeader(http.StatusOK)
22+
secureHandler(w, r)
23+
} else {
24+
// 3) If mismatch or missing, respond with 401
25+
w.WriteHeader(http.StatusUnauthorized)
26+
}
27+
})
28+
}
29+
30+
// helloHandler returns "Hello!" on GET /hello
31+
func helloHandler(w http.ResponseWriter, r *http.Request) {
32+
fmt.Fprint(w, "Hello!")
33+
}
34+
35+
// secureHandler returns "You are authorized!" on GET /secure
36+
func secureHandler(w http.ResponseWriter, r *http.Request) {
37+
fmt.Fprint(w, "You are authorized!")
38+
}
39+
40+
// SetupServer configures the HTTP routes with the authentication middleware.
41+
func SetupServer() http.Handler {
42+
mux := http.NewServeMux()
43+
44+
// Public route: /hello (no auth required)
45+
mux.HandleFunc("/hello", helloHandler)
46+
47+
// Secure route: /secure
48+
// Wrap with AuthMiddleware
49+
secureRoute := http.HandlerFunc(secureHandler)
50+
mux.Handle("/secure", AuthMiddleware(secureRoute))
51+
52+
return mux
53+
}
54+
55+
func main() {
56+
// Optional: you can run a real server for local testing
57+
http.ListenAndServe(":8080", SetupServer())
58+
}

0 commit comments

Comments
 (0)