/
render.go
67 lines (61 loc) · 1.59 KB
/
render.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
package context
import (
"encoding/xml"
"net/http"
)
var xmlContentType = []string{"application/xml; charset=utf-8"}
var plainContentType = []string{"text/plain; charset=utf-8"}
//Render render from bytes
func (ctx *Context) Render(bytes []byte) {
//debug
//fmt.Println("response msg = ", string(bytes))
if ctx.HttType == "fasthttp" {
//debug
//fmt.Println("response msg = ", string(bytes))
ctx.FastHttpCtx.Response.SetStatusCode(200)
_, err := ctx.FastHttpCtx.Write(bytes)
if err != nil {
panic(err)
}
}else{
//debug
//fmt.Println("response msg = ", string(bytes))
ctx.Writer.WriteHeader(200)
_, err := ctx.Writer.Write(bytes)
if err != nil {
panic(err)
}
}
}
//String render from string
func (ctx *Context) String(str string) {
if ctx.HttType == "fasthttp" {
if val := ctx.FastHttpCtx.Response.Header.Peek("Content-Type"); len(val) == 0 {
ctx.FastHttpCtx.Response.Header.Set("Content-Type",plainContentType[0])
}
}else{
writeContextType(ctx.Writer, plainContentType)
}
ctx.Render([]byte(str))
}
//XML render to xml
func (ctx *Context) XML(obj interface{}) {
if ctx.HttType == "fasthttp" {
if val := ctx.FastHttpCtx.Response.Header.Peek("Content-Type"); len(val) == 0 {
ctx.FastHttpCtx.Response.Header.Set("Content-Type",xmlContentType[0])
}
}else {
writeContextType(ctx.Writer, xmlContentType)
}
bytes, err := xml.Marshal(obj)
if err != nil {
panic(err)
}
ctx.Render(bytes)
}
func writeContextType(w http.ResponseWriter, value []string) {
header := w.Header()
if val := header["Content-Type"]; len(val) == 0 {
header["Content-Type"] = value
}
}