69f40ad1 by astaxie

add some useful function

1. Router
2. SetSession/GetSession/DelSession
3. RenderString
4. str2html/htmlquote/htmlunquote
5. move the template Function to util.go
1 parent 74d8952c
...@@ -153,7 +153,7 @@ func (app *App) Run() { ...@@ -153,7 +153,7 @@ func (app *App) Run() {
153 } 153 }
154 } 154 }
155 155
156 func (app *App) RegisterController(path string, c ControllerInterface) *App { 156 func (app *App) Router(path string, c ControllerInterface) *App {
157 app.Handlers.Add(path, c) 157 app.Handlers.Add(path, c)
158 return app 158 return app
159 } 159 }
...@@ -192,7 +192,12 @@ func (app *App) AccessLog(ctx *Context) { ...@@ -192,7 +192,12 @@ func (app *App) AccessLog(ctx *Context) {
192 } 192 }
193 193
194 func RegisterController(path string, c ControllerInterface) *App { 194 func RegisterController(path string, c ControllerInterface) *App {
195 BeeApp.RegisterController(path, c) 195 BeeApp.Router(path, c)
196 return BeeApp
197 }
198
199 func Router(path string, c ControllerInterface) *App {
200 BeeApp.Router(path, c)
196 return BeeApp 201 return BeeApp
197 } 202 }
198 203
...@@ -213,8 +218,8 @@ func FilterPrefixPath(path string, filter http.HandlerFunc) *App { ...@@ -213,8 +218,8 @@ func FilterPrefixPath(path string, filter http.HandlerFunc) *App {
213 218
214 func Run() { 219 func Run() {
215 if PprofOn { 220 if PprofOn {
216 BeeApp.RegisterController(`/debug/pprof`, &ProfController{}) 221 BeeApp.Router(`/debug/pprof`, &ProfController{})
217 BeeApp.RegisterController(`/debug/pprof/:pp([\w]+)`, &ProfController{}) 222 BeeApp.Router(`/debug/pprof/:pp([\w]+)`, &ProfController{})
218 } 223 }
219 if SessionOn { 224 if SessionOn {
220 GlobalSessions, _ = session.NewManager(SessionProvider, SessionName, SessionGCMaxLifetime) 225 GlobalSessions, _ = session.NewManager(SessionProvider, SessionName, SessionGCMaxLifetime)
......
...@@ -82,6 +82,21 @@ func (c *Controller) Options() { ...@@ -82,6 +82,21 @@ func (c *Controller) Options() {
82 http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405) 82 http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405)
83 } 83 }
84 84
85 func (c *Controller) SetSession(name string, value interface{}) {
86 ss := c.StartSession()
87 ss.Set(name, value)
88 }
89
90 func (c *Controller) GetSession(name string) interface{} {
91 ss := c.StartSession()
92 return ss.Get(name)
93 }
94
95 func (c *Controller) DelSession(name string) {
96 ss := c.StartSession()
97 ss.Delete(name)
98 }
99
85 func (c *Controller) Render() error { 100 func (c *Controller) Render() error {
86 rb, err := c.RenderBytes() 101 rb, err := c.RenderBytes()
87 102
...@@ -96,32 +111,29 @@ func (c *Controller) Render() error { ...@@ -96,32 +111,29 @@ func (c *Controller) Render() error {
96 return nil 111 return nil
97 } 112 }
98 113
114 func (c *Controller) RenderString() (string, error) {
115 b, e := c.RenderBytes()
116 return string(b), e
117 }
118
99 func (c *Controller) RenderBytes() ([]byte, error) { 119 func (c *Controller) RenderBytes() ([]byte, error) {
100 //if the controller has set layout, then first get the tplname's content set the content to the layout 120 //if the controller has set layout, then first get the tplname's content set the content to the layout
101 var t *template.Template
102 var err error
103 if c.Layout != "" { 121 if c.Layout != "" {
104 if c.TplNames == "" { 122 if c.TplNames == "" {
105 c.TplNames = c.ChildName + "/" + c.Ctx.Request.Method + "." + c.TplExt 123 c.TplNames = c.ChildName + "/" + c.Ctx.Request.Method + "." + c.TplExt
106 } 124 }
107 if RunMode == "dev" { 125 if RunMode == "dev" {
108 t, err = template.New("beegoTemplate").Funcs(beegoTplFuncMap).ParseFiles(path.Join(ViewsPath, c.TplNames), path.Join(ViewsPath, c.Layout)) 126 BuildTemplate(ViewsPath)
109 if err != nil {
110 Trace("template ParseFiles err:", err)
111 }
112 } else {
113 subdir := path.Dir(c.TplNames)
114 t = BeeTemplates[subdir]
115 } 127 }
128 subdir := path.Dir(c.TplNames)
116 _, file := path.Split(c.TplNames) 129 _, file := path.Split(c.TplNames)
117
118 newbytes := bytes.NewBufferString("") 130 newbytes := bytes.NewBufferString("")
119 t.ExecuteTemplate(newbytes, file, c.Data) 131 BeeTemplates[subdir].ExecuteTemplate(newbytes, file, c.Data)
120 tplcontent, _ := ioutil.ReadAll(newbytes) 132 tplcontent, _ := ioutil.ReadAll(newbytes)
121 c.Data["LayoutContent"] = template.HTML(string(tplcontent)) 133 c.Data["LayoutContent"] = template.HTML(string(tplcontent))
122 _, file = path.Split(c.Layout) 134 _, file = path.Split(c.Layout)
123 ibytes := bytes.NewBufferString("") 135 ibytes := bytes.NewBufferString("")
124 err := t.ExecuteTemplate(ibytes, file, c.Data) 136 err := BeeTemplates[subdir].ExecuteTemplate(ibytes, file, c.Data)
125 if err != nil { 137 if err != nil {
126 Trace("template Execute err:", err) 138 Trace("template Execute err:", err)
127 } 139 }
...@@ -132,17 +144,12 @@ func (c *Controller) RenderBytes() ([]byte, error) { ...@@ -132,17 +144,12 @@ func (c *Controller) RenderBytes() ([]byte, error) {
132 c.TplNames = c.ChildName + "/" + c.Ctx.Request.Method + "." + c.TplExt 144 c.TplNames = c.ChildName + "/" + c.Ctx.Request.Method + "." + c.TplExt
133 } 145 }
134 if RunMode == "dev" { 146 if RunMode == "dev" {
135 t, err = template.New("beegoTemplate").Funcs(beegoTplFuncMap).ParseFiles(path.Join(ViewsPath, c.TplNames)) 147 BuildTemplate(ViewsPath)
136 if err != nil {
137 Trace("template ParseFiles err:", err)
138 }
139 } else {
140 subdir := path.Dir(c.TplNames)
141 t = BeeTemplates[subdir]
142 } 148 }
149 subdir := path.Dir(c.TplNames)
143 _, file := path.Split(c.TplNames) 150 _, file := path.Split(c.TplNames)
144 ibytes := bytes.NewBufferString("") 151 ibytes := bytes.NewBufferString("")
145 err := t.ExecuteTemplate(ibytes, file, c.Data) 152 err := BeeTemplates[subdir].ExecuteTemplate(ibytes, file, c.Data)
146 if err != nil { 153 if err != nil {
147 Trace("template Execute err:", err) 154 Trace("template Execute err:", err)
148 } 155 }
......
...@@ -5,14 +5,11 @@ package beego ...@@ -5,14 +5,11 @@ package beego
5 import ( 5 import (
6 "errors" 6 "errors"
7 "fmt" 7 "fmt"
8 "github.com/russross/blackfriday"
9 "html/template" 8 "html/template"
10 "os" 9 "os"
11 "path" 10 "path"
12 "path/filepath" 11 "path/filepath"
13 "regexp"
14 "strings" 12 "strings"
15 "time"
16 ) 13 )
17 14
18 var ( 15 var (
...@@ -32,110 +29,9 @@ func init() { ...@@ -32,110 +29,9 @@ func init() {
32 beegoTplFuncMap["compare"] = Compare 29 beegoTplFuncMap["compare"] = Compare
33 beegoTplFuncMap["substr"] = Substr 30 beegoTplFuncMap["substr"] = Substr
34 beegoTplFuncMap["html2str"] = Html2str 31 beegoTplFuncMap["html2str"] = Html2str
35 } 32 beegoTplFuncMap["str2html"] = Str2html
36 33 beegoTplFuncMap["htmlquote"] = Htmlquote
37 // MarkDown parses a string in MarkDown format and returns HTML. Used by the template parser as "markdown" 34 beegoTplFuncMap["htmlunquote"] = Htmlunquote
38 func MarkDown(raw string) (output template.HTML) {
39 input := []byte(raw)
40 bOutput := blackfriday.MarkdownBasic(input)
41 output = template.HTML(string(bOutput))
42 return
43 }
44
45 func Substr(s string, start, length int) string {
46 bt := []rune(s)
47 if start < 0 {
48 start = 0
49 }
50 var end int
51 if (start + length) > (len(bt) - 1) {
52 end = len(bt) - 1
53 } else {
54 end = start + length
55 }
56 return string(bt[start:end])
57 }
58
59 // Html2str() returns escaping text convert from html
60 func Html2str(html string) string {
61 src := string(html)
62
63 //将HTML标签全转换成小写
64 re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
65 src = re.ReplaceAllStringFunc(src, strings.ToLower)
66
67 //去除STYLE
68 re, _ = regexp.Compile("\\<style[\\S\\s]+?\\</style\\>")
69 src = re.ReplaceAllString(src, "")
70
71 //去除SCRIPT
72 re, _ = regexp.Compile("\\<script[\\S\\s]+?\\</script\\>")
73 src = re.ReplaceAllString(src, "")
74
75 //去除所有尖括号内的HTML代码,并换成换行符
76 re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
77 src = re.ReplaceAllString(src, "\n")
78
79 //去除连续的换行符
80 re, _ = regexp.Compile("\\s{2,}")
81 src = re.ReplaceAllString(src, "\n")
82
83 return strings.TrimSpace(src)
84 }
85
86 // DateFormat takes a time and a layout string and returns a string with the formatted date. Used by the template parser as "dateformat"
87 func DateFormat(t time.Time, layout string) (datestring string) {
88 datestring = t.Format(layout)
89 return
90 }
91
92 // Date takes a PHP like date func to Go's time fomate
93 func Date(t time.Time, format string) (datestring string) {
94 patterns := []string{
95 // year
96 "Y", "2006", // A full numeric representation of a year, 4 digits Examples: 1999 or 2003
97 "y", "06", //A two digit representation of a year Examples: 99 or 03
98
99 // month
100 "m", "01", // Numeric representation of a month, with leading zeros 01 through 12
101 "n", "1", // Numeric representation of a month, without leading zeros 1 through 12
102 "M", "Jan", // A short textual representation of a month, three letters Jan through Dec
103 "F", "January", // A full textual representation of a month, such as January or March January through December
104
105 // day
106 "d", "02", // Day of the month, 2 digits with leading zeros 01 to 31
107 "j", "2", // Day of the month without leading zeros 1 to 31
108
109 // week
110 "D", "Mon", // A textual representation of a day, three letters Mon through Sun
111 "l", "Monday", // A full textual representation of the day of the week Sunday through Saturday
112
113 // time
114 "g", "3", // 12-hour format of an hour without leading zeros 1 through 12
115 "G", "15", // 24-hour format of an hour without leading zeros 0 through 23
116 "h", "03", // 12-hour format of an hour with leading zeros 01 through 12
117 "H", "15", // 24-hour format of an hour with leading zeros 00 through 23
118
119 "a", "pm", // Lowercase Ante meridiem and Post meridiem am or pm
120 "A", "PM", // Uppercase Ante meridiem and Post meridiem AM or PM
121
122 "i", "04", // Minutes with leading zeros 00 to 59
123 "s", "05", // Seconds, with leading zeros 00 through 59
124 }
125 replacer := strings.NewReplacer(patterns...)
126 format = replacer.Replace(format)
127 datestring = t.Format(format)
128 return
129 }
130
131 // Compare is a quick and dirty comparison function. It will convert whatever you give it to strings and see if the two values are equal.
132 // Whitespace is trimmed. Used by the template parser as "eq"
133 func Compare(a, b interface{}) (equal bool) {
134 equal = false
135 if strings.TrimSpace(fmt.Sprintf("%v", a)) == strings.TrimSpace(fmt.Sprintf("%v", b)) {
136 equal = true
137 }
138 return
139 } 35 }
140 36
141 // AddFuncMap let user to register a func in the template 37 // AddFuncMap let user to register a func in the template
......
1 package beego 1 package beego
2 2
3 import ( 3 import (
4 "fmt"
5 "github.com/russross/blackfriday"
6 "html/template"
7 "regexp"
4 "strings" 8 "strings"
5 "time" 9 "time"
6 ) 10 )
...@@ -12,3 +16,157 @@ func webTime(t time.Time) string { ...@@ -12,3 +16,157 @@ func webTime(t time.Time) string {
12 } 16 }
13 return ftime 17 return ftime
14 } 18 }
19
20 // MarkDown parses a string in MarkDown format and returns HTML. Used by the template parser as "markdown"
21 func MarkDown(raw string) (output template.HTML) {
22 input := []byte(raw)
23 bOutput := blackfriday.MarkdownBasic(input)
24 output = template.HTML(string(bOutput))
25 return
26 }
27
28 func Substr(s string, start, length int) string {
29 bt := []rune(s)
30 if start < 0 {
31 start = 0
32 }
33 var end int
34 if (start + length) > (len(bt) - 1) {
35 end = len(bt) - 1
36 } else {
37 end = start + length
38 }
39 return string(bt[start:end])
40 }
41
42 // Html2str() returns escaping text convert from html
43 func Html2str(html string) string {
44 src := string(html)
45
46 //将HTML标签全转换成小写
47 re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
48 src = re.ReplaceAllStringFunc(src, strings.ToLower)
49
50 //去除STYLE
51 re, _ = regexp.Compile("\\<style[\\S\\s]+?\\</style\\>")
52 src = re.ReplaceAllString(src, "")
53
54 //去除SCRIPT
55 re, _ = regexp.Compile("\\<script[\\S\\s]+?\\</script\\>")
56 src = re.ReplaceAllString(src, "")
57
58 //去除所有尖括号内的HTML代码,并换成换行符
59 re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
60 src = re.ReplaceAllString(src, "\n")
61
62 //去除连续的换行符
63 re, _ = regexp.Compile("\\s{2,}")
64 src = re.ReplaceAllString(src, "\n")
65
66 return strings.TrimSpace(src)
67 }
68
69 // DateFormat takes a time and a layout string and returns a string with the formatted date. Used by the template parser as "dateformat"
70 func DateFormat(t time.Time, layout string) (datestring string) {
71 datestring = t.Format(layout)
72 return
73 }
74
75 // Date takes a PHP like date func to Go's time fomate
76 func Date(t time.Time, format string) (datestring string) {
77 patterns := []string{
78 // year
79 "Y", "2006", // A full numeric representation of a year, 4 digits Examples: 1999 or 2003
80 "y", "06", //A two digit representation of a year Examples: 99 or 03
81
82 // month
83 "m", "01", // Numeric representation of a month, with leading zeros 01 through 12
84 "n", "1", // Numeric representation of a month, without leading zeros 1 through 12
85 "M", "Jan", // A short textual representation of a month, three letters Jan through Dec
86 "F", "January", // A full textual representation of a month, such as January or March January through December
87
88 // day
89 "d", "02", // Day of the month, 2 digits with leading zeros 01 to 31
90 "j", "2", // Day of the month without leading zeros 1 to 31
91
92 // week
93 "D", "Mon", // A textual representation of a day, three letters Mon through Sun
94 "l", "Monday", // A full textual representation of the day of the week Sunday through Saturday
95
96 // time
97 "g", "3", // 12-hour format of an hour without leading zeros 1 through 12
98 "G", "15", // 24-hour format of an hour without leading zeros 0 through 23
99 "h", "03", // 12-hour format of an hour with leading zeros 01 through 12
100 "H", "15", // 24-hour format of an hour with leading zeros 00 through 23
101
102 "a", "pm", // Lowercase Ante meridiem and Post meridiem am or pm
103 "A", "PM", // Uppercase Ante meridiem and Post meridiem AM or PM
104
105 "i", "04", // Minutes with leading zeros 00 to 59
106 "s", "05", // Seconds, with leading zeros 00 through 59
107 }
108 replacer := strings.NewReplacer(patterns...)
109 format = replacer.Replace(format)
110 datestring = t.Format(format)
111 return
112 }
113
114 // Compare is a quick and dirty comparison function. It will convert whatever you give it to strings and see if the two values are equal.
115 // Whitespace is trimmed. Used by the template parser as "eq"
116 func Compare(a, b interface{}) (equal bool) {
117 equal = false
118 if strings.TrimSpace(fmt.Sprintf("%v", a)) == strings.TrimSpace(fmt.Sprintf("%v", b)) {
119 equal = true
120 }
121 return
122 }
123
124 func Str2html(raw string) template.HTML {
125 return template.HTML(raw)
126 }
127
128 func Htmlquote(src string) string {
129 //HTML编码为实体符号
130 /*
131 Encodes `text` for raw use in HTML.
132 >>> htmlquote("<'&\\">")
133 '&lt;&#39;&amp;&quot;&gt;'
134 */
135
136 text := string(src)
137
138 text = strings.Replace(text, "&", "&amp;", -1) // Must be done first!
139 text = strings.Replace(text, "<", "&lt;", -1)
140 text = strings.Replace(text, ">", "&gt;", -1)
141 text = strings.Replace(text, "'", "&#39;", -1)
142 text = strings.Replace(text, "\"", "&quot;", -1)
143 text = strings.Replace(text, "“", "&ldquo;", -1)
144 text = strings.Replace(text, "”", "&rdquo;", -1)
145 text = strings.Replace(text, " ", "&nbsp;", -1)
146
147 return strings.TrimSpace(text)
148 }
149
150 func Htmlunquote(src string) string {
151 //实体符号解释为HTML
152 /*
153 Decodes `text` that's HTML quoted.
154 >>> htmlunquote('&lt;&#39;&amp;&quot;&gt;')
155 '<\\'&">'
156 */
157
158 // strings.Replace(s, old, new, n)
159 // 在s字符串中,把old字符串替换为new字符串,n表示替换的次数,小于0表示全部替换
160
161 text := string(src)
162 text = strings.Replace(text, "&nbsp;", " ", -1)
163 text = strings.Replace(text, "&rdquo;", "”", -1)
164 text = strings.Replace(text, "&ldquo;", "“", -1)
165 text = strings.Replace(text, "&quot;", "\"", -1)
166 text = strings.Replace(text, "&#39;", "'", -1)
167 text = strings.Replace(text, "&gt;", ">", -1)
168 text = strings.Replace(text, "&lt;", "<", -1)
169 text = strings.Replace(text, "&amp;", "&", -1) // Must be done last!
170
171 return strings.TrimSpace(text)
172 }
......
Styling with Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!