moira

Форк
0
/
context.go 
134 строки · 4.9 Кб
1
package middleware
2

3
import (
4
	"context"
5
	"fmt"
6
	"net/http"
7
	"strconv"
8

9
	"github.com/go-chi/chi"
10
	"github.com/go-chi/render"
11

12
	"go.avito.ru/DO/moira"
13
	"go.avito.ru/DO/moira/api"
14
)
15

16
func ConfigContext(config api.Config) func(next http.Handler) http.Handler {
17
	return func(next http.Handler) http.Handler {
18
		return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
19
			ctx := context.WithValue(request.Context(), configKey, config)
20
			next.ServeHTTP(writer, request.WithContext(ctx))
21
		})
22
	}
23
}
24

25
// DatabaseContext sets to requests context configured database
26
func DatabaseContext(database moira.Database) func(next http.Handler) http.Handler {
27
	return func(next http.Handler) http.Handler {
28
		return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
29
			ctx := context.WithValue(request.Context(), databaseKey, database)
30
			next.ServeHTTP(writer, request.WithContext(ctx))
31
		})
32
	}
33
}
34

35
// UserContext get x-webauth-user header and sets it in request context, if header is empty sets empty string
36
func UserContext(next http.Handler) http.Handler {
37
	return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
38
		userLogin := request.Header.Get("x-webauth-user")
39
		ctx := context.WithValue(request.Context(), loginKey, userLogin)
40
		next.ServeHTTP(writer, request.WithContext(ctx))
41
	})
42
}
43

44
// TriggerContext gets triggerId from parsed URI corresponding to trigger routes and set it to request context
45
func TriggerContext(next http.Handler) http.Handler {
46
	return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
47
		triggerID := chi.URLParam(request, "triggerId")
48
		if triggerID == "" {
49
			render.Render(writer, request, api.ErrorInvalidRequest(fmt.Errorf("TriggerID must be set")))
50
			return
51
		}
52
		ctx := context.WithValue(request.Context(), triggerIDKey, triggerID)
53
		next.ServeHTTP(writer, request.WithContext(ctx))
54
	})
55
}
56

57
// ContactContext gets contactID from parsed URI corresponding to trigger routes and set it to request context
58
func ContactContext(next http.Handler) http.Handler {
59
	return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
60
		contactID := chi.URLParam(request, "contactId")
61
		if contactID == "" {
62
			render.Render(writer, request, api.ErrorInvalidRequest(fmt.Errorf("ContactID must be set")))
63
			return
64
		}
65
		ctx := context.WithValue(request.Context(), contactIDKey, contactID)
66
		next.ServeHTTP(writer, request.WithContext(ctx))
67
	})
68
}
69

70
// TagContext gets tagName from parsed URI corresponding to tag routes and set it to request context
71
func TagContext(next http.Handler) http.Handler {
72
	return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
73
		tag := chi.URLParam(request, "tag")
74
		if tag == "" {
75
			render.Render(writer, request, api.ErrorInvalidRequest(fmt.Errorf("Tag must be set")))
76
			return
77
		}
78
		ctx := context.WithValue(request.Context(), tagKey, tag)
79
		next.ServeHTTP(writer, request.WithContext(ctx))
80
	})
81
}
82

83
// SubscriptionContext gets subscriptionId from parsed URI corresponding to subscription routes and set it to request context
84
func SubscriptionContext(next http.Handler) http.Handler {
85
	return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
86
		triggerID := chi.URLParam(request, "subscriptionId")
87
		if triggerID == "" {
88
			render.Render(writer, request, api.ErrorInvalidRequest(fmt.Errorf("SubscriptionId must be set")))
89
			return
90
		}
91
		ctx := context.WithValue(request.Context(), subscriptionIDKey, triggerID)
92
		next.ServeHTTP(writer, request.WithContext(ctx))
93
	})
94
}
95

96
// Paginate gets page and size values from URI query and set it to request context. If query has not values sets given values
97
func Paginate(defaultPage, defaultSize int64) func(next http.Handler) http.Handler {
98
	return func(next http.Handler) http.Handler {
99
		return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
100
			page, err := strconv.ParseInt(request.URL.Query().Get("p"), 10, 64)
101
			if err != nil {
102
				page = defaultPage
103
			}
104
			size, err := strconv.ParseInt(request.URL.Query().Get("size"), 10, 64)
105
			if err != nil {
106
				size = defaultSize
107
			}
108

109
			ctxPage := context.WithValue(request.Context(), pageKey, page)
110
			ctxSize := context.WithValue(ctxPage, sizeKey, size)
111
			next.ServeHTTP(writer, request.WithContext(ctxSize))
112
		})
113
	}
114
}
115

116
// DateRange gets from and to values from URI query and set it to request context. If query has not values sets given values
117
func DateRange(defaultFrom, defaultTo string) func(next http.Handler) http.Handler {
118
	return func(next http.Handler) http.Handler {
119
		return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
120
			from := request.URL.Query().Get("from")
121
			if from == "" {
122
				from = defaultFrom
123
			}
124
			to := request.URL.Query().Get("to")
125
			if to == "" {
126
				to = defaultTo
127
			}
128

129
			ctxPage := context.WithValue(request.Context(), fromKey, from)
130
			ctxSize := context.WithValue(ctxPage, toKey, to)
131
			next.ServeHTTP(writer, request.WithContext(ctxSize))
132
		})
133
	}
134
}
135

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.