This repository was archived by the owner on Jun 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcontext.go
104 lines (90 loc) · 2.25 KB
/
context.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
// Goro
//
// Created by Yakka
// http://theyakka.com
//
// Copyright (c) 2019 Yakka LLC.
// All rights reserved.
// See the LICENSE file for licensing details and requirements.
package goro
import (
"net/http"
"sync"
)
const (
StateKeyHasExecutedPreFilters = "_goro.skey.hasExecutedPreFilters"
StateKeyHasExecutedPostFilters = "_goro.skey.hasExecutedPostFilters"
)
type HandlerContext struct {
sync.RWMutex
Request *http.Request
ResponseWriter http.ResponseWriter
Parameters *Parameters
Meta map[string]interface{}
Path string
CatchAllValue string
Errors []RoutingError
router *Router
state map[string]interface{}
internalState map[string]interface{}
}
func NewHandlerContext(request *http.Request, responseWriter http.ResponseWriter, router *Router) *HandlerContext {
return &HandlerContext{
Request: request,
ResponseWriter: responseWriter,
router: router,
Meta: map[string]interface{}{},
state: map[string]interface{}{},
internalState: map[string]interface{}{},
}
}
func (hc *HandlerContext) SetState(key string, value interface{}) {
hc.Lock()
hc.state[key] = value
hc.Unlock()
}
func (hc *HandlerContext) GetState(key string) interface{} {
hc.RLock()
state := hc.state[key]
hc.RUnlock()
return state
}
func (hc *HandlerContext) GetStateString(key string) string {
stateVal := hc.GetState(key)
if stateString, ok := stateVal.(string); ok {
return stateString
}
return ""
}
func (hc *HandlerContext) GetStateInt(key string) int {
stateVal := hc.GetState(key)
if stateString, ok := stateVal.(int); ok {
return stateString
}
return 0
}
func (hc *HandlerContext) ClearState(key string) {
hc.Lock()
hc.state[key] = nil
hc.Unlock()
}
func (hc *HandlerContext) HasError() bool {
return len(hc.Errors) > 0
}
func (hc *HandlerContext) ErrorForStatus(status int) RoutingError {
for _, err := range hc.Errors {
if err.StatusCode == status {
return err
}
}
return EmptyRoutingError()
}
func (hc *HandlerContext) HasErrorForStatus(status int) bool {
return !IsEmptyRoutingError(hc.ErrorForStatus(status))
}
func (hc *HandlerContext) FirstError() RoutingError {
if len(hc.Errors) > 0 {
return hc.Errors[0]
}
return EmptyRoutingError()
}