-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext.go
55 lines (45 loc) · 1.11 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
package mux
import (
"encoding/json"
"fmt"
"net/http"
)
type H map[string]interface{}
type Context struct {
Writer http.ResponseWriter
Request *http.Request
Params map[string]string
StatusCode int
}
func NewContext(w http.ResponseWriter, r *http.Request) *Context {
return &Context{
Writer: w,
Request: r,
}
}
func (c *Context) PostForm(key string) string {
return c.Request.FormValue(key)
}
func (c *Context) Query(key string) string {
return c.Request.URL.Query().Get(key)
}
func (c *Context) Status(code int) {
c.StatusCode = code
c.Writer.WriteHeader(code)
}
func (c *Context) SetHeader(key string, value string) {
c.Writer.Header().Set(key, value)
}
func (c *Context) String(code int, format string, values ...interface{}) {
c.SetHeader("Content-Type", "text/plain")
c.Status(code)
c.Writer.Write([]byte(fmt.Sprintf(format, values...)))
}
func (c *Context) JSON(code int, obj interface{}) {
c.SetHeader("Content-Type", "application/json")
c.Status(code)
encoder := json.NewEncoder(c.Writer)
if err := encoder.Encode(obj); err != nil {
http.Error(c.Writer, err.Error(), 500)
}
}