Skip to content

Commit 8f4dde6

Browse files
authored
Add solution for Challenge 5 by tufstraka (#1581)
Auto-merged after 2 days with all checks passing. PR: #1581 Author: @tufstraka
1 parent 47ec2c3 commit 8f4dde6

1 file changed

Lines changed: 56 additions & 0 deletions

File tree

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+
16+
token := r.Header.Get("X-Auth-Token")
17+
18+
if token == "" || token != validToken {
19+
http.Error(w,"", http.StatusUnauthorized)
20+
21+
return
22+
}
23+
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)