-
Notifications
You must be signed in to change notification settings - Fork 5
/
middleware.go
86 lines (74 loc) · 2.11 KB
/
middleware.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package main
import (
"context"
"fmt"
"net/http"
"strconv"
"strings"
"github.com/go-chi/chi/v5"
)
func disablePaginate(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), "pagination", "1,-1")
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func paginate(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
pageNumStr := r.URL.Query().Get("page[number]")
var pageNum int
pageSizeStr := r.URL.Query().Get("page[size]")
var pageSize int
var err error
if pageNumStr != "" {
pageNum, err = strconv.Atoi(pageNumStr)
if err != nil || pageNum <= 0 {
w.WriteHeader(http.StatusBadRequest)
return
}
} else {
pageNum = 1
}
if pageSizeStr != "" {
pageSize, err = strconv.Atoi(pageSizeStr)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
} else {
pageSize = 16
}
ctx := context.WithValue(r.Context(), "pagination", fmt.Sprintf("%d,%d", pageNum, pageSize))
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func useCors(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
ctx := context.WithValue(r.Context(), "cors", true)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func languageChecker(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
lang := strings.ToLower(chi.URLParam(r, "lang"))
switch lang {
case "en", "fr", "de", "es", "pt":
ctx := context.WithValue(r.Context(), "lang", lang)
next.ServeHTTP(w, r.WithContext(ctx))
default:
w.WriteHeader(http.StatusBadRequest)
}
})
}
func ankamaIdExtractor(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ankamaId, err := strconv.Atoi(chi.URLParam(r, "ankamaId"))
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
ctx := context.WithValue(r.Context(), "ankamaId", ankamaId)
next.ServeHTTP(w, r.WithContext(ctx))
})
}