-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpractice.go
More file actions
50 lines (41 loc) · 1.09 KB
/
practice.go
File metadata and controls
50 lines (41 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package main
import (
"context"
"fmt"
"net/http"
)
type userKey int // Custom type for context key
const authenticatedUserKey userKey = 0
type User struct {
ID string
Email string
Roles []string
}
func AuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Simulate authentication
authenticatedUser := User{
ID: "user123",
Email: "test@example.com",
Roles: []string{"admin", "user"},
}
// Store user in context
ctx := context.WithValue(r.Context(), authenticatedUserKey, authenticatedUser)
r = r.WithContext(ctx)
next.ServeHTTP(w, r)
})
}
func ProtectedHandler(w http.ResponseWriter, r *http.Request) {
// Retrieve user from context
user, ok := r.Context().Value(authenticatedUserKey).(User)
if !ok {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
fmt.Fprintf(w, "Welcome, %s! Your roles: %v", user.Email, user.Roles)
}
func main2() {
mux := http.NewServeMux()
mux.Handle("/protected", AuthMiddleware(http.HandlerFunc(ProtectedHandler)))
http.ListenAndServe(":8080", mux)
}