-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.go
71 lines (54 loc) · 1.21 KB
/
handler.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
package khanmux
import (
"encoding/json"
"encoding/xml"
"net/http"
)
type Context struct {
Request *http.Request
Handler Handler
Response http.ResponseWriter
}
func (c *Context) JSON(status int, data interface{}) error {
c.Response.Header().Set("Content-Type", "application/json; charset=utf-8")
c.Response.WriteHeader(status)
err := json.NewEncoder(c.Response).Encode(data)
if err != nil {
return err
}
return nil
}
func (c *Context) XML(status int, data interface{}) error {
c.Response.Header().Set("Content-Type", "application/xml; charset=utf-8")
c.Response.WriteHeader(status)
x, err := xml.MarshalIndent(data, " ", " ")
c.Response.Write(x)
if err != nil {
return err
}
return nil
}
func (c *Context) Find(i interface{}) error {
err := json.NewDecoder(c.Request.Body).Decode(&i)
if err != nil {
return err
}
return nil
}
func (c *Context) Query(key string) string {
param := c.Request.URL.Query().Get(key)
return param
}
type Response struct {
StatusCode int
Data map[string]interface{}
}
type Handler func(c Context) error
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
context := Context{
Request: r,
Handler: h,
Response: w,
}
h(context)
}