-
Notifications
You must be signed in to change notification settings - Fork 1
/
response.go
83 lines (70 loc) · 1.89 KB
/
response.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 soggy
import (
"net/http"
"encoding/json"
"bytes"
"os"
"io"
"strconv"
)
const (
POWERED_BY_HEADER = "X-Powered-By"
POWERED_BY = "sogginess"
)
const (
HTML_CONTENT_TYPE = "text/html; charset=utf-8"
JSON_CONTENT_TYPE = "application/json; charset=utf-8"
)
type Response struct {
http.ResponseWriter
server *Server
}
func (res *Response) Render(status int, file string, params interface{}) (err interface{}) {
buf := new(bytes.Buffer)
ext, template := res.server.TemplatePath(file)
if _, err := os.Stat(template); err != nil {
return err
}
engine := res.server.TemplateEngines[ext[1:]]
if engine == nil {
return "No engine defined for " + ext[1:]
}
err = engine(buf, template, params)
if err != nil {
return err
}
res.Set("Content-Type", HTML_CONTENT_TYPE)
res.Set("Content-Length", strconv.Itoa(buf.Len()))
res.WriteHeader(status)
_, err = io.Copy(res, buf)
return err
}
func (res *Response) Html(status int, html string) (err interface{}) {
res.Set("Content-Type", HTML_CONTENT_TYPE)
res.Set("Content-Length", strconv.Itoa(len(html)))
res.WriteHeader(status)
_, err = res.WriteString(html)
return err
}
func (res *Response) Json(status int, jsonIn interface{}) (err interface{}) {
res.Set("Content-Type", JSON_CONTENT_TYPE)
jsonOut, err := json.Marshal(jsonIn)
if err == nil {
res.Set("Content-Length", strconv.Itoa(len(jsonOut)))
res.WriteHeader(status)
_, err = res.Write(jsonOut)
}
return err
}
func (res *Response) WriteString(s string) (int, error) {
res.Set("Content-Length", strconv.Itoa(len(s)))
return res.Write([]byte(s))
}
func (res *Response) Set(header, value string) {
res.Header().Set(header, value)
}
func NewResponse(res http.ResponseWriter, server *Server) *Response {
wrappedResponse := &Response{res, server}
wrappedResponse.Set(POWERED_BY_HEADER, POWERED_BY)
return wrappedResponse;
}