Skip to content

Commit 5a9c081

Browse files
mick4711timlkko
authored andcommitted
Add solution for Challenge 5 by mick4711 (RezaSi#65)
1 parent 410eecd commit 5a9c081

File tree

1 file changed

+56
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)