-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathweb.go
63 lines (51 loc) · 1.44 KB
/
web.go
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
51
52
53
54
55
56
57
58
59
60
61
62
63
package main
import (
"context"
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/", authMiddleware(handler))
log.Fatal(http.ListenAndServe(":8080", nil))
}
func handler(w http.ResponseWriter, r *http.Request) {
var currentUser User
// 컨텍스트에서 값을 가져옴
if v := r.Context().Value("current_user"); v == nil {
// "current_user"가 존재하지 않으면 401 에러 리턴
http.Error(w, "Not Authorized", http.StatusUnauthorized)
return
} else {
u, ok := v.(User)
if !ok {
// 타입이 User가 아니면 401 에러 리턴
http.Error(w, "Not Authorized", http.StatusUnauthorized)
return
}
currentUser = u
}
fmt.Fprintf(w, "Hi I am %s", currentUser.Name)
}
func authMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// 현재 세션 정보를 확인하여 currentUser 생성
currentUser, err := getCurrentUser(r)
if err != nil {
http.Error(w, "Not Authorized", http.StatusUnauthorized)
return
}
// 기본 컨텍스트(r.Context())에 current_user 값을 담은 새로운 컨텍스트 생성
ctx := context.WithValue(r.Context(), "current_user", currentUser)
// 기존 http.Request의 컨텍스트를 변경
nextRequest := r.WithContext(ctx)
// 다음 handlerFunc 호출
next(w, nextRequest)
}
}
func getCurrentUser(r *http.Request) (User, error) {
return User{Name: "Jaehue"}, nil
}
type User struct {
Name string
}