-
Notifications
You must be signed in to change notification settings - Fork 0
/
web.go
executable file
·76 lines (58 loc) · 1.52 KB
/
web.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
// Title:提供web渲染常用的一些方法
//
// Description:
//
// Author:black
//
// Createtime:2013-09-17 14:37
//
// Version:1.0
//
// 修改历史:版本号 修改日期 修改人 修改说明
//
// 1.0 2013-09-17 14:37 black 创建文档
package commonlib
import (
"bytes"
"encoding/json"
"net/http"
"strings"
"text/template"
)
//html模板合成方法
//参考的调用方式 RenderTemplate(w, r, "home.html", m, nil, "../template/home.html", "../template/nav.html")
func RenderTemplate(w http.ResponseWriter, r *http.Request, templateName string, data map[string]interface{}, funcMap template.FuncMap, templateFiles ...string) {
var err error
var t *template.Template
var buf bytes.Buffer
t = template.New(templateName)
if funcMap != nil {
//注册一些常用函数
t = t.Funcs(funcMap)
}
t, err = t.ParseFiles(templateFiles...)
if err != nil {
panic(err)
}
err = t.Execute(&buf, data)
if err != nil {
panic(err)
}
w.Write(buf.Bytes())
}
//JSON数据输出,需要指定换行符号的替换符号
func OutputJson(w http.ResponseWriter, object interface{}, newlineReplace string) {
b, err := json.Marshal(object)
if err != nil {
return
}
str := string(b)
str = strings.Replace(str, "\n", newlineReplace, -1)
str = strings.Replace(str, "\n\r", newlineReplace, -1)
str = strings.Replace(str, "\r\n", newlineReplace, -1)
str = strings.Replace(str, "\r", newlineReplace, -1)
/*
str = strings.Replace(str, "\"", "\\\"", -1)
str = strings.Replace(str, "'", "\\'", -1)*/
w.Write([]byte(str))
}