-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunction.go
More file actions
73 lines (62 loc) · 1.74 KB
/
function.go
File metadata and controls
73 lines (62 loc) · 1.74 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package ghastly
import (
"encoding/json"
"net/http"
)
type Response struct {
Body any
Headers map[string]string
StatusCode int
Cookies []http.Cookie
}
type Middleware[T any] func(state *T, response *Response, request *http.Request, next func(*T) *T, cancel func(*T)) *T
type Service[T any] interface {
HandleRequest(*T, *Response, *http.Request) *T
}
type RegisteredHandler[T any] struct {
Server *Ghastly[T]
Method string
Endpoint string
FullPath string
Middlewares []Middleware[T]
Service Service[T]
}
func run[T any](handler *RegisteredHandler[T], response *Response, request *http.Request, state *T, index int, cancelled bool) *T {
if cancelled {
return state
}
if index < len(handler.Middlewares) {
return handler.Middlewares[index](state, response, request, func(state *T) *T {
return run(handler, response, request, state, index+1, false)
}, func(state *T) {
run(handler, response, request, state, index, true)
})
} else {
return handler.Service.HandleRequest(state, response, request)
}
}
func (handler *RegisteredHandler[T]) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) {
var state T
response := &Response{
StatusCode: -1,
}
_ = run(handler, response, request, &state, 0, false)
if response.StatusCode == -1 {
response.StatusCode = 200
}
responseWriter.WriteHeader(response.StatusCode)
for _, cookie := range response.Cookies {
http.SetCookie(responseWriter, &cookie)
}
for key, value := range response.Headers {
responseWriter.Header().Add(key, value)
}
body, err := json.Marshal(response.Body)
if err != nil {
panic("error - failed marshaling body")
}
_, err = responseWriter.Write(body)
if err != nil {
panic("error -failed writing body")
}
}