-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext.go
83 lines (69 loc) · 1.59 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
package sal
import (
"encoding/json"
"net/http"
"sync"
)
var (
ctxPool = sync.Pool{
New: func() any {
return &Ctx{}
},
}
)
type Ctx struct {
w http.ResponseWriter
Request *http.Request
}
type SalHandlerFunc func(c *Ctx)
func (f SalHandlerFunc) ServeHTTP(c *Ctx) {
f(c)
}
func (c *Ctx) Json(content any, status int) error {
c.w.Header().Add("Content-Type", "application/json")
c.w.WriteHeader(status)
if err := json.NewEncoder(c.w).Encode(content); err != nil {
return err
}
return nil
}
func (c *Ctx) Error(message string, status int) error {
return c.Json(map[string]string{"error": message}, status)
}
func (c *Ctx) Text(content string, status int) error {
c.w.Header().Add("Content-Type", "text/plain")
c.w.WriteHeader(status)
if _, err := c.w.Write([]byte(content)); err != nil {
return err
}
return nil
}
func (c *Ctx) Redirect(url string, status int) {
http.Redirect(c.w, c.Request, url, status)
}
func (c *Ctx) HTML(content string, status int) error {
c.w.Header().Add("Content-Type", "text/html")
c.w.WriteHeader(status)
if _, err := c.w.Write([]byte(content)); err != nil {
return err
}
return nil
}
func (c *Ctx) File(filePath string) error {
http.ServeFile(c.w, c.Request, filePath)
return nil
}
func (c *Ctx) NoContent(status int) {
c.w.WriteHeader(status)
}
func (c *Ctx) Header(key, value string) {
c.w.Header().Set(key, value)
}
func (c *Ctx) Binary(content []byte, contentType string, status int) error {
c.w.Header().Add("Content-Type", contentType)
c.w.WriteHeader(status)
if _, err := c.w.Write(content); err != nil {
return err
}
return nil
}