-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathslick.go
188 lines (151 loc) · 4.28 KB
/
slick.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
package slick
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
"os"
"strings"
"github.com/a-h/templ"
"github.com/joho/godotenv"
"github.com/julienschmidt/httprouter"
)
type Plug func(Handler) Handler
type Handler func(c *Context) error
type ErrorHandler func(error, *Context) error
type Context struct {
Response http.ResponseWriter
Request *http.Request
ctx context.Context
params httprouter.Params
}
func newContext(w http.ResponseWriter, r *http.Request, params httprouter.Params) *Context {
return &Context{
Response: w,
Request: r,
ctx: context.Background(),
params: params,
}
}
func (c *Context) Param(name string) string {
return c.params.ByName(name)
}
func (c *Context) Query(name string) string {
return c.Request.URL.Query().Get(name)
}
func (c *Context) FormValue(name string) string {
return c.Request.FormValue(name)
}
func (c *Context) Render(component templ.Component) error {
return component.Render(c.ctx, c.Response)
}
func (c *Context) Redirect(url string, code int) error {
if code < http.StatusMultipleChoices || code > http.StatusTemporaryRedirect {
return errors.New("invalid redirect code")
}
http.Redirect(c.Response, c.Request, url, code)
return nil
}
func (c *Context) JSON(status int, v any) error {
c.Response.Header().Set("Content-Type", "application/json")
c.Response.WriteHeader(status)
return json.NewDecoder(c.Request.Body).Decode(&v)
}
func (c *Context) Text(status int, t string) error {
c.Response.Header().Set("Content-Type", "text/plain")
c.Response.WriteHeader(status)
_, err := c.Response.Write([]byte(t))
return err
}
func (c *Context) Set(key string, value any) {
c.ctx = context.WithValue(c.ctx, key, value)
}
func (c *Context) Get(key string) any {
return c.ctx.Value(key)
}
type Slick struct {
ErrorHandler ErrorHandler
router *httprouter.Router
plugs []Plug
}
func New() *Slick {
return &Slick{
router: httprouter.New(),
ErrorHandler: defaultErrorHandler,
}
}
type methodNotAllowedHandler struct {
handler Handler
}
func (h methodNotAllowedHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx := newContext(w, r, httprouter.Params{})
h.handler(ctx)
}
func (s *Slick) MethodNotAllowed(h Handler) {
s.router.MethodNotAllowed = methodNotAllowedHandler{h}
}
func (s *Slick) Plug(plugs ...Plug) {
s.plugs = append(s.plugs, plugs...)
}
func (s *Slick) Start() error {
if err := godotenv.Load(); err != nil {
return err
}
// Retrieve and sanitize listen address from env
listenAddr := os.Getenv("SLICK_HTTP_LISTEN_ADDR")
listenAddr = strings.TrimSpace(listenAddr)
// If listen address is not set, use default host and port
if listenAddr == "" {
listenAddr = ":3000"
}
// Print the URL where the app is running
browsableURL := listenAddr
if strings.HasPrefix(browsableURL, ":") {
browsableURL = "localhost" + browsableURL
}
fmt.Printf("slick app running at http://%s\n", browsableURL)
// Start the HTTP server
return http.ListenAndServe(listenAddr, s.router)
}
func (s *Slick) add(method, path string, h Handler, plugs ...Plug) {
s.router.Handle(method, path, s.makeHTTPRouterHandle(h, plugs...))
}
func (s *Slick) Get(path string, h Handler, plugs ...Plug) {
s.add("GET", path, h, plugs...)
}
func (s *Slick) Post(path string, h Handler, plugs ...Plug) {
s.add("POST", path, h, plugs...)
}
func (s *Slick) Put(path string, h Handler, plugs ...Plug) {
s.add("PUT", path, h, plugs...)
}
func (s *Slick) Delete(path string, h Handler, plugs ...Plug) {
s.add("DELETE", path, h, plugs...)
}
func (s *Slick) Head(path string, h Handler, plugs ...Plug) {
s.add("HEAD", path, h, plugs...)
}
func (s *Slick) Options(path string, h Handler, plugs ...Plug) {
s.add("OPTIONS", path, h, plugs...)
}
func (s *Slick) makeHTTPRouterHandle(h Handler, plugs ...Plug) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
ctx := newContext(w, r, params)
for i := len(plugs) - 1; i >= 0; i-- {
h = plugs[i](h)
}
for i := len(s.plugs) - 1; i >= 0; i-- {
h = s.plugs[i](h)
}
if err := h(ctx); err != nil {
// todo: handle the error from the error handler huh?
s.ErrorHandler(err, ctx)
}
}
}
func defaultErrorHandler(err error, c *Context) error {
slog.Error("error", "err", err)
return nil
}