action.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977
  1. package xweb
  2. import (
  3. "bytes"
  4. "compress/flate"
  5. "compress/gzip"
  6. "crypto/hmac"
  7. "crypto/md5"
  8. "crypto/sha1"
  9. "encoding/base64"
  10. "encoding/hex"
  11. "encoding/json"
  12. "encoding/xml"
  13. "errors"
  14. "fmt"
  15. "html/template"
  16. "io"
  17. "io/ioutil"
  18. "mime"
  19. "mime/multipart"
  20. "net/http"
  21. "net/url"
  22. "os"
  23. "path"
  24. "reflect"
  25. "regexp"
  26. "runtime"
  27. "strconv"
  28. "strings"
  29. "sync"
  30. "time"
  31. "github.com/go-xweb/httpsession"
  32. "github.com/go-xweb/log"
  33. "github.com/go-xweb/uuid"
  34. )
  35. type ActionOption struct {
  36. AutoMapForm bool
  37. CheckXsrf bool
  38. }
  39. // An Action object or it's substruct is created for every incoming HTTP request.
  40. // It provides information
  41. // about the request, including the http.Request object, the GET and POST params,
  42. // and acts as a Writer for the response.
  43. type Action struct {
  44. Request *http.Request
  45. App *App
  46. Option *ActionOption
  47. http.ResponseWriter
  48. C reflect.Value
  49. session *httpsession.Session
  50. T T
  51. f T
  52. RootTemplate *template.Template
  53. RequestBody []byte
  54. StatusCode int
  55. }
  56. type Mapper struct {
  57. }
  58. type T map[string]interface{}
  59. func XsrfName() string {
  60. return XSRF_TAG
  61. }
  62. //[SWH|+]:
  63. // Protocol returns request protocol name, such as HTTP/1.1 .
  64. func (c *Action) Protocol() string {
  65. return c.Request.Proto
  66. }
  67. // Uri returns full request url with query string, fragment.
  68. func (c *Action) Uri() string {
  69. return c.Request.RequestURI
  70. }
  71. // Url returns request url path (without query string, fragment).
  72. func (c *Action) Url() string {
  73. return c.Request.URL.String()
  74. }
  75. // Site returns base site url as scheme://domain type.
  76. func (c *Action) Site() string {
  77. schecm, _ := c.App.GetConfig("schecm").(string)
  78. if schecm == "" {
  79. schecm = c.Scheme()
  80. }
  81. return schecm + "://" + c.Domain()
  82. }
  83. // Scheme returns request scheme as "http" or "https".
  84. func (c *Action) Scheme() string {
  85. if c.Request.URL.Scheme != "" {
  86. return c.Request.URL.Scheme
  87. } else if c.Request.TLS == nil {
  88. return "http"
  89. } else {
  90. return "https"
  91. }
  92. }
  93. // Domain returns host name.
  94. // Alias of Host method.
  95. func (c *Action) Domain() string {
  96. return c.Host()
  97. }
  98. // Host returns host name.
  99. // if no host info in request, return localhost.
  100. func (c *Action) Host() string {
  101. if c.Request.Host != "" {
  102. hostParts := strings.Split(c.Request.Host, ":")
  103. if len(hostParts) > 0 {
  104. return hostParts[0]
  105. }
  106. return c.Request.Host
  107. }
  108. return "localhost"
  109. }
  110. // Is returns boolean of this request is on given method, such as Is("POST").
  111. func (c *Action) Is(method string) bool {
  112. return c.Method() == method
  113. }
  114. // IsAjax returns boolean of this request is generated by ajax.
  115. func (c *Action) IsAjax() bool {
  116. return c.Header("X-Requested-With") == "XMLHttpRequest"
  117. }
  118. // IsSecure returns boolean of this request is in https.
  119. func (c *Action) IsSecure() bool {
  120. return c.Scheme() == "https"
  121. }
  122. // IsSecure returns boolean of this request is in webSocket.
  123. func (c *Action) IsWebsocket() bool {
  124. return c.Header("Upgrade") == "websocket"
  125. }
  126. // IsSecure returns boolean of whether file uploads in this request or not..
  127. func (c *Action) IsUpload() bool {
  128. return c.Request.MultipartForm != nil
  129. }
  130. // IP returns request client ip.
  131. // if in proxy, return first proxy id.
  132. // if error, return 127.0.0.1.
  133. func (c *Action) IP() string {
  134. ips := c.Proxy()
  135. if len(ips) > 0 && ips[0] != "" {
  136. return ips[0]
  137. }
  138. ip := strings.Split(c.Request.RemoteAddr, ":")
  139. if len(ip) > 0 {
  140. if ip[0] != "[" {
  141. return ip[0]
  142. }
  143. }
  144. return "127.0.0.1"
  145. }
  146. // Proxy returns proxy client ips slice.
  147. func (c *Action) Proxy() []string {
  148. if ips := c.Header("X-Forwarded-For"); ips != "" {
  149. return strings.Split(ips, ",")
  150. }
  151. return []string{}
  152. }
  153. // Refer returns http referer header.
  154. func (c *Action) Refer() string {
  155. return c.Header("Referer")
  156. }
  157. // SubDomains returns sub domain string.
  158. // if aa.bb.domain.com, returns aa.bb .
  159. func (c *Action) SubDomains() string {
  160. parts := strings.Split(c.Host(), ".")
  161. return strings.Join(parts[len(parts)-2:], ".")
  162. }
  163. // Port returns request client port.
  164. // when error or empty, return 80.
  165. func (c *Action) Port() int {
  166. parts := strings.Split(c.Request.Host, ":")
  167. if len(parts) == 2 {
  168. port, _ := strconv.Atoi(parts[1])
  169. return port
  170. }
  171. return 80
  172. }
  173. // UserAgent returns request client user agent string.
  174. func (c *Action) UserAgent() string {
  175. return c.Header("User-Agent")
  176. }
  177. // Query returns input data item string by a given string.
  178. func (c *Action) Query(key string) string {
  179. c.Request.ParseForm()
  180. return c.Request.Form.Get(key)
  181. }
  182. // Header returns request header item string by a given string.
  183. func (c *Action) Header(key string) string {
  184. return c.Request.Header.Get(key)
  185. }
  186. // Cookie returns request cookie item string by a given key.
  187. // if non-existed, return empty string.
  188. func (c *Action) Cookie(key string) string {
  189. ck, err := c.Request.Cookie(key)
  190. if err != nil {
  191. return ""
  192. }
  193. return ck.Value
  194. }
  195. // Body returns the raw request body data as bytes.
  196. func (c *Action) Body() []byte {
  197. if len(c.RequestBody) > 0 {
  198. return c.RequestBody
  199. }
  200. requestbody, _ := ioutil.ReadAll(c.Request.Body)
  201. c.Request.Body.Close()
  202. bf := bytes.NewBuffer(requestbody)
  203. c.Request.Body = ioutil.NopCloser(bf)
  204. c.RequestBody = requestbody
  205. return requestbody
  206. }
  207. func (c *Action) DisableHttpCache() {
  208. c.SetHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT")
  209. c.SetHeader("Last-Modified", webTime(time.Now().UTC()))
  210. c.SetHeader("Cache-Control", "no-store, no-cache, must-revalidate")
  211. c.SetHeader("Cache-Control", "post-check=0, pre-check=0")
  212. c.SetHeader("Pragma", "no-cache")
  213. }
  214. func (c *Action) HttpCache(content []byte) bool {
  215. h := md5.New()
  216. h.Write(content)
  217. Etag := hex.EncodeToString(h.Sum(nil))
  218. //c.SetHeader("Connection", "keep-alive")
  219. c.SetHeader("X-Cache", "HIT from COSCMS-Page-Cache")
  220. //c.SetHeader("X-Cache", "HIT from COSCMS-Page-Cache 2013-12-02 17:16:01")
  221. if inm := c.Header("If-None-Match"); inm != "" && inm == Etag {
  222. h := c.ResponseWriter.Header()
  223. delete(h, "Content-Type")
  224. delete(h, "Content-Length")
  225. c.ResponseWriter.WriteHeader(http.StatusNotModified)
  226. return true
  227. }
  228. c.SetHeader("Etag", Etag)
  229. c.SetHeader("Cache-Control", "public,max-age=1")
  230. return false
  231. }
  232. // Body sets response body content.
  233. // if EnableGzip, compress content string.
  234. // it sends out response body directly.
  235. func (c *Action) SetBody(content []byte) error {
  236. if c.App.AppConfig.EnableHttpCache && c.HttpCache(content) {
  237. return nil
  238. }
  239. output_writer := c.ResponseWriter.(io.Writer)
  240. if c.App.Server.Config.EnableGzip == true && c.Header("Accept-Encoding") != "" {
  241. splitted := strings.SplitN(c.Header("Accept-Encoding"), ",", -1)
  242. encodings := make([]string, len(splitted))
  243. for i, val := range splitted {
  244. encodings[i] = strings.TrimSpace(val)
  245. }
  246. for _, val := range encodings {
  247. if val == "gzip" {
  248. c.SetHeader("Content-Encoding", "gzip")
  249. output_writer, _ = gzip.NewWriterLevel(c.ResponseWriter, gzip.BestSpeed)
  250. break
  251. } else if val == "deflate" {
  252. c.SetHeader("Content-Encoding", "deflate")
  253. output_writer, _ = flate.NewWriter(c.ResponseWriter, flate.BestSpeed)
  254. break
  255. }
  256. }
  257. } else {
  258. c.SetHeader("Content-Length", strconv.Itoa(len(content)))
  259. }
  260. _, err := output_writer.Write(content)
  261. switch output_writer.(type) {
  262. case *gzip.Writer:
  263. output_writer.(*gzip.Writer).Close()
  264. case *flate.Writer:
  265. output_writer.(*flate.Writer).Close()
  266. }
  267. return err
  268. }
  269. //[SWH|+];
  270. func (c *Action) XsrfValue() string {
  271. var val string = ""
  272. cookie, err := c.GetCookie(XSRF_TAG)
  273. if err != nil {
  274. val = uuid.NewRandom().String()
  275. c.SetCookie(NewCookie(XSRF_TAG, val, int64(c.App.AppConfig.SessionTimeout)))
  276. } else {
  277. val = cookie.Value
  278. }
  279. return val
  280. }
  281. func (c *Action) XsrfFormHtml() template.HTML {
  282. if c.App.AppConfig.CheckXsrf {
  283. return template.HTML(fmt.Sprintf(`<input type="hidden" name="%v" value="%v" />`,
  284. XSRF_TAG, c.XsrfValue()))
  285. }
  286. return template.HTML("")
  287. }
  288. // WriteString writes string data into the response object.
  289. func (c *Action) WriteBytes(bytes []byte) error {
  290. //_, err := c.ResponseWriter.Write(bytes)
  291. err := c.SetBody(bytes) //[SWH|+]
  292. if err != nil {
  293. c.App.Error("Error during write:", err)
  294. }
  295. return err
  296. }
  297. func (c *Action) Write(content string, values ...interface{}) error {
  298. if len(values) > 0 {
  299. content = fmt.Sprintf(content, values...)
  300. }
  301. //_, err := c.ResponseWriter.Write([]byte(content))
  302. err := c.SetBody([]byte(content)) //[SWH|+]
  303. if err != nil {
  304. c.App.Error("Error during write:", err)
  305. }
  306. return err
  307. }
  308. // Abort is a helper method that sends an HTTP header and an optional
  309. // body. It is useful for returning 4xx or 5xx errors.
  310. // Once it has been called, any return value from the handler will
  311. // not be written to the response.
  312. func (c *Action) Abort(status int, body string) error {
  313. c.StatusCode = status
  314. return c.App.error(c.ResponseWriter, status, body)
  315. }
  316. // Redirect is a helper method for 3xx redirects.
  317. func (c *Action) Redirect(url string, status ...int) error {
  318. if len(status) == 0 {
  319. c.StatusCode = 302
  320. } else {
  321. c.StatusCode = status[0]
  322. }
  323. return c.App.Redirect(c.ResponseWriter, c.Request.URL.Path, url, status...)
  324. }
  325. // Notmodified writes a 304 HTTP response
  326. func (c *Action) NotModified() {
  327. c.StatusCode = 304
  328. c.ResponseWriter.WriteHeader(304)
  329. }
  330. // NotFound writes a 404 HTTP response
  331. func (c *Action) NotFound(message string) error {
  332. c.StatusCode = 404
  333. return c.Abort(404, message)
  334. }
  335. // ParseStruct mapping forms' name and values to struct's field
  336. // For example:
  337. // <form>
  338. // <input name="user.id"/>
  339. // <input name="user.name"/>
  340. // <input name="user.age"/>
  341. // </form>
  342. //
  343. // type User struct {
  344. // Id int64
  345. // Name string
  346. // Age string
  347. // }
  348. //
  349. // var user User
  350. // err := action.MapForm(&user)
  351. //
  352. func (c *Action) MapForm(st interface{}, names ...string) error {
  353. v := reflect.ValueOf(st)
  354. var name string
  355. if len(names) == 0 {
  356. name = UnTitle(v.Type().Elem().Name())
  357. } else {
  358. name = names[0]
  359. }
  360. return c.App.namedStructMap(v.Elem(), c.Request, name)
  361. }
  362. // ContentType sets the Content-Type header for an HTTP response.
  363. // For example, c.ContentType("json") sets the content-type to "application/json"
  364. // If the supplied value contains a slash (/) it is set as the Content-Type
  365. // verbatim. The return value is the content type as it was
  366. // set, or an empty string if none was found.
  367. func (c *Action) SetContentType(val string) string {
  368. var ctype string
  369. if strings.ContainsRune(val, '/') {
  370. ctype = val
  371. } else {
  372. if !strings.HasPrefix(val, ".") {
  373. val = "." + val
  374. }
  375. ctype = mime.TypeByExtension(val)
  376. }
  377. if ctype != "" {
  378. c.SetHeader("Content-Type", ctype)
  379. }
  380. return ctype
  381. }
  382. // SetCookie adds a cookie header to the response.
  383. func (c *Action) SetCookie(cookie *http.Cookie) {
  384. c.SetHeader("Set-Cookie", cookie.String())
  385. }
  386. func (c *Action) GetCookie(cookieName string) (*http.Cookie, error) {
  387. return c.Request.Cookie(cookieName)
  388. }
  389. func getCookieSig(key string, val []byte, timestamp string) string {
  390. hm := hmac.New(sha1.New, []byte(key))
  391. hm.Write(val)
  392. hm.Write([]byte(timestamp))
  393. hex := fmt.Sprintf("%02x", hm.Sum(nil))
  394. return hex
  395. }
  396. func (c *Action) SetSecureCookie(name string, val string, age int64) {
  397. //base64 encode the val
  398. if len(c.App.AppConfig.CookieSecret) == 0 {
  399. c.App.Error("Secret Key for secure cookies has not been set. Please assign a cookie secret to web.Config.CookieSecret.")
  400. return
  401. }
  402. var buf bytes.Buffer
  403. encoder := base64.NewEncoder(base64.StdEncoding, &buf)
  404. encoder.Write([]byte(val))
  405. encoder.Close()
  406. vs := buf.String()
  407. vb := buf.Bytes()
  408. timestamp := strconv.FormatInt(time.Now().Unix(), 10)
  409. sig := getCookieSig(c.App.AppConfig.CookieSecret, vb, timestamp)
  410. cookie := strings.Join([]string{vs, timestamp, sig}, "|")
  411. c.SetCookie(NewCookie(name, cookie, age))
  412. }
  413. func (c *Action) GetSecureCookie(name string) (string, bool) {
  414. for _, cookie := range c.Request.Cookies() {
  415. if cookie.Name != name {
  416. continue
  417. }
  418. parts := strings.SplitN(cookie.Value, "|", 3)
  419. val := parts[0]
  420. timestamp := parts[1]
  421. sig := parts[2]
  422. if getCookieSig(c.App.AppConfig.CookieSecret, []byte(val), timestamp) != sig {
  423. return "", false
  424. }
  425. ts, _ := strconv.ParseInt(timestamp, 0, 64)
  426. if time.Now().Unix()-31*86400 > ts {
  427. return "", false
  428. }
  429. buf := bytes.NewBufferString(val)
  430. encoder := base64.NewDecoder(base64.StdEncoding, buf)
  431. res, _ := ioutil.ReadAll(encoder)
  432. return string(res), true
  433. }
  434. return "", false
  435. }
  436. func (c *Action) Method() string {
  437. return c.Request.Method
  438. }
  439. func (c *Action) Go(m string, anotherc ...interface{}) error {
  440. var t reflect.Type
  441. if len(anotherc) > 0 {
  442. t = reflect.TypeOf(anotherc[0]).Elem()
  443. } else {
  444. t = reflect.TypeOf(c.C.Interface()).Elem()
  445. }
  446. root, ok := c.App.ActionsPath[t]
  447. if !ok {
  448. return NotFound()
  449. }
  450. uris := strings.Split(m, "?")
  451. tag, ok := t.FieldByName(uris[0])
  452. if !ok {
  453. return NotFound()
  454. }
  455. tagStr := tag.Tag.Get("xweb")
  456. var rPath string
  457. if tagStr != "" {
  458. p := tagStr
  459. ts := strings.Split(tagStr, " ")
  460. if len(ts) >= 2 {
  461. p = ts[1]
  462. }
  463. rPath = path.Join(root, p, m[len(uris[0]):])
  464. } else {
  465. rPath = path.Join(root, m)
  466. }
  467. rPath = strings.Replace(rPath, "//", "/", -1)
  468. return c.Redirect(rPath)
  469. }
  470. func (c *Action) Flush() {
  471. flusher, _ := c.ResponseWriter.(http.Flusher)
  472. flusher.Flush()
  473. }
  474. func (c *Action) BasePath() string {
  475. return c.App.BasePath
  476. }
  477. func (c *Action) Namespace() string {
  478. return c.App.ActionsPath[c.C.Type()]
  479. }
  480. func (c *Action) Debug(params ...interface{}) {
  481. c.App.Debug(params...)
  482. }
  483. func (c *Action) Info(params ...interface{}) {
  484. c.App.Info(params...)
  485. }
  486. func (c *Action) Warn(params ...interface{}) {
  487. c.App.Warn(params...)
  488. }
  489. func (c *Action) Error(params ...interface{}) {
  490. c.App.Error(params...)
  491. }
  492. func (c *Action) Fatal(params ...interface{}) {
  493. c.App.Fatal(params...)
  494. }
  495. func (c *Action) Panic(params ...interface{}) {
  496. c.App.Panic(params...)
  497. }
  498. func (c *Action) Debugf(format string, params ...interface{}) {
  499. c.App.Debugf(format, params...)
  500. }
  501. func (c *Action) Infof(format string, params ...interface{}) {
  502. c.App.Infof(format, params...)
  503. }
  504. func (c *Action) Warnf(format string, params ...interface{}) {
  505. c.App.Warnf(format, params...)
  506. }
  507. func (c *Action) Errorf(format string, params ...interface{}) {
  508. c.App.Errorf(format, params...)
  509. }
  510. func (c *Action) Fatalf(format string, params ...interface{}) {
  511. c.App.Fatalf(format, params...)
  512. }
  513. func (c *Action) Panicf(format string, params ...interface{}) {
  514. c.App.Panicf(format, params...)
  515. }
  516. // Include method provide to template for {{include "xx.tmpl"}}
  517. func (c *Action) Include(tmplName string) interface{} {
  518. t := c.RootTemplate.New(tmplName)
  519. t.Funcs(c.GetFuncs())
  520. content, err := c.getTemplate(tmplName)
  521. if err != nil {
  522. c.Errorf("RenderTemplate %v read err: %s", tmplName, err)
  523. return ""
  524. }
  525. constr := string(content)
  526. //[SWH|+]call hook
  527. if r, err := XHook.Call("BeforeRender", constr, c); err == nil {
  528. constr = XHook.String(r[0])
  529. }
  530. tmpl, err := t.Parse(constr)
  531. if err != nil {
  532. c.Errorf("Parse %v err: %v", tmplName, err)
  533. return ""
  534. }
  535. newbytes := bytes.NewBufferString("")
  536. err = tmpl.Execute(newbytes, c.C.Elem().Interface())
  537. if err != nil {
  538. c.Errorf("Parse %v err: %v", tmplName, err)
  539. return ""
  540. }
  541. tplcontent, err := ioutil.ReadAll(newbytes)
  542. if err != nil {
  543. c.Errorf("Parse %v err: %v", tmplName, err)
  544. return ""
  545. }
  546. return template.HTML(string(tplcontent))
  547. }
  548. // render the template with vars map, you can have zero or one map
  549. func (c *Action) NamedRender(name, content string, params ...*T) error {
  550. defer func() {
  551. if r := recover(); r != nil {
  552. log.Println(r)
  553. for skip := 0; skip < 100; skip++ {
  554. _, file, line, ok := runtime.Caller(skip)
  555. if !ok {
  556. break
  557. }
  558. go log.Printf("%v,%v\n", file, line)
  559. }
  560. }
  561. }()
  562. c.f["oinclude"] = c.Include
  563. if c.App.AppConfig.SessionOn {
  564. c.f["session"] = c.GetSession
  565. }
  566. c.f["cookie"] = c.Cookie
  567. c.f["XsrfFormHtml"] = c.XsrfFormHtml
  568. c.f["XsrfValue"] = c.XsrfValue
  569. if len(params) > 0 {
  570. c.AddTmplVars(params[0])
  571. }
  572. c.RootTemplate = template.New(name)
  573. c.RootTemplate.Funcs(c.GetFuncs())
  574. //[SWH|+]call hook
  575. if r, err := XHook.Call("BeforeRender", content, c); err == nil {
  576. content = XHook.String(r[0])
  577. }
  578. content = newInclude(c, content)
  579. tmpl, err := c.RootTemplate.Parse(content)
  580. if err == nil {
  581. newbytes := bytes.NewBufferString("")
  582. err = tmpl.Execute(newbytes, c.C.Elem().Interface())
  583. if err == nil {
  584. tplcontent, err := ioutil.ReadAll(newbytes)
  585. if err == nil {
  586. //[SWH|+]call hook
  587. if r, err := XHook.Call("AfterRender", tplcontent, c); err == nil {
  588. if ret := XHook.Value(r, 0); ret != nil {
  589. tplcontent = ret.([]byte)
  590. }
  591. }
  592. err = c.SetBody(tplcontent) //[SWH|+]
  593. //_, err = c.ResponseWriter.Write(tplcontent)
  594. }
  595. }
  596. }
  597. return err
  598. }
  599. func (c *Action) getTemplate(tmpl string) ([]byte, error) {
  600. if c.App.AppConfig.CacheTemplates {
  601. return c.App.TemplateMgr.GetTemplate(tmpl)
  602. }
  603. path := c.App.getTemplatePath(tmpl)
  604. if path == "" {
  605. return nil, errors.New(fmt.Sprintf("No template file %v found", path))
  606. }
  607. content, err := ioutil.ReadFile(path)
  608. if err == nil {
  609. content = newIncludeIntmpl(c.App.AppConfig.TemplateDir, content)
  610. }
  611. return content, err
  612. }
  613. // render the template with vars map, you can have zero or one map
  614. func (c *Action) Render(tmpl string, params ...*T) error {
  615. content, err := c.getTemplate(tmpl)
  616. if err == nil {
  617. err = c.NamedRender(tmpl, string(content), params...)
  618. }
  619. return err
  620. }
  621. //仅生成网页内容
  622. var regInclude = regexp.MustCompile(`\{\{\s*include\s*"(.*?\.html)"\}\}`)
  623. func (c *Action) NamedRender4Cache(name, content string, params ...*T) ([]byte, error) {
  624. c.f["oinclude"] = c.Include
  625. if c.App.AppConfig.SessionOn {
  626. c.f["session"] = c.GetSession
  627. }
  628. c.f["cookie"] = c.Cookie
  629. c.f["XsrfFormHtml"] = c.XsrfFormHtml
  630. c.f["XsrfValue"] = c.XsrfValue
  631. if len(params) > 0 {
  632. c.AddTmplVars(params[0])
  633. }
  634. c.RootTemplate = template.New(name)
  635. c.RootTemplate.Funcs(c.GetFuncs())
  636. //[SWH|+]call hook
  637. if r, err := XHook.Call("BeforeRender", content, c); err == nil {
  638. content = XHook.String(r[0])
  639. }
  640. content = newInclude(c, content)
  641. tmpl, err := c.RootTemplate.Parse(content)
  642. if err == nil {
  643. newbytes := bytes.NewBufferString("")
  644. err = tmpl.Execute(newbytes, c.C.Elem().Interface())
  645. if err == nil {
  646. tplcontent, err := ioutil.ReadAll(newbytes)
  647. if err == nil {
  648. //[SWH|+]call hook
  649. if r, err := XHook.Call("AfterRender", tplcontent, c); err == nil {
  650. if ret := XHook.Value(r, 0); ret != nil {
  651. tplcontent = ret.([]byte)
  652. }
  653. }
  654. //err = c.SetBody(tplcontent) //[SWH|+]
  655. //_, err = c.ResponseWriter.Write(tplcontent)
  656. return tplcontent, nil
  657. }
  658. }
  659. }
  660. return nil, err
  661. }
  662. //生成可缓存的数据但并未写到流中
  663. func (c *Action) Render4Cache(tmpl string, params ...*T) ([]byte, error) {
  664. content, err := c.getTemplate(tmpl)
  665. if err == nil {
  666. return c.NamedRender4Cache(tmpl, string(content), params...)
  667. }
  668. return nil, err
  669. }
  670. var FuncLock = &sync.Mutex{}
  671. func (c *Action) GetFuncs() template.FuncMap {
  672. FuncLock.Lock()
  673. funcs := template.FuncMap{}
  674. for k, v := range c.App.FuncMaps {
  675. funcs[k] = v
  676. }
  677. FuncLock.Unlock()
  678. if c.f != nil {
  679. for k, v := range c.f {
  680. funcs[k] = v
  681. }
  682. }
  683. return funcs
  684. }
  685. func (c *Action) SetConfig(name string, value interface{}) {
  686. c.App.Config[name] = value
  687. }
  688. func (c *Action) GetConfig(name string) interface{} {
  689. return c.App.Config[name]
  690. }
  691. func (c *Action) RenderString(content string, params ...*T) error {
  692. h := md5.New()
  693. h.Write([]byte(content))
  694. name := h.Sum(nil)
  695. return c.NamedRender(string(name), content, params...)
  696. }
  697. // SetHeader sets a response header. the current value
  698. // of that header will be overwritten .
  699. func (c *Action) SetHeader(key string, value string) {
  700. c.ResponseWriter.Header().Set(key, value)
  701. }
  702. // add a name value for template
  703. func (c *Action) AddTmplVar(name string, varOrFunc interface{}) {
  704. if varOrFunc == nil {
  705. c.T[name] = varOrFunc
  706. return
  707. }
  708. if reflect.ValueOf(varOrFunc).Type().Kind() == reflect.Func {
  709. c.f[name] = varOrFunc
  710. } else {
  711. c.T[name] = varOrFunc
  712. }
  713. }
  714. // add names and values for template
  715. func (c *Action) AddTmplVars(t *T) {
  716. for name, value := range *t {
  717. c.AddTmplVar(name, value)
  718. }
  719. }
  720. func (c *Action) ServeJson(obj interface{}) {
  721. content, err := json.MarshalIndent(obj, "", " ")
  722. if err != nil {
  723. http.Error(c.ResponseWriter, err.Error(), http.StatusInternalServerError)
  724. return
  725. }
  726. c.SetHeader("Content-Length", strconv.Itoa(len(content)))
  727. c.ResponseWriter.Header().Set("Content-Type", "application/json")
  728. c.ResponseWriter.Write(content)
  729. }
  730. func (c *Action) ServeXml(obj interface{}) {
  731. content, err := xml.Marshal(obj)
  732. if err != nil {
  733. http.Error(c.ResponseWriter, err.Error(), http.StatusInternalServerError)
  734. return
  735. }
  736. c.SetHeader("Content-Length", strconv.Itoa(len(content)))
  737. c.ResponseWriter.Header().Set("Content-Type", "application/xml")
  738. c.ResponseWriter.Write(content)
  739. }
  740. func (c *Action) ServeFile(fpath string) {
  741. c.ResponseWriter.Header().Del("Content-Type")
  742. http.ServeFile(c.ResponseWriter, c.Request, fpath)
  743. }
  744. func (c *Action) GetSlice(key string) []string {
  745. return c.Request.Form[key]
  746. }
  747. func (c *Action) GetForm() url.Values {
  748. return c.Request.Form
  749. }
  750. //增加_过滤脚本等
  751. func FilterXSS(str string) string {
  752. str = strings.Replace(str, "<", "&#60;", -1)
  753. str = strings.Replace(str, ">", "&#62;", -1)
  754. str = strings.Replace(str, "%3C", "&#60;", -1)
  755. str = strings.Replace(str, "%3E", "&#62;", -1)
  756. str = strings.Replace(str, "expression", "expression", -1)
  757. str = strings.Replace(str, "javascript", "javascript", -1)
  758. return str
  759. }
  760. //增加_原GetString方法
  761. func (c *Action) GetStringComm(key string) string {
  762. s := c.GetSlice(key)
  763. if len(s) > 0 {
  764. return s[0]
  765. }
  766. return ""
  767. }
  768. //修改_防Xss注入
  769. func (c *Action) GetString(key string) string {
  770. return FilterXSS(c.GetStringComm(key))
  771. }
  772. func (c *Action) GetInteger(key string) (int, error) {
  773. return strconv.Atoi(c.GetString(key))
  774. }
  775. func (c *Action) GetInt(key string) (int64, error) {
  776. return strconv.ParseInt(c.GetString(key), 10, 64)
  777. }
  778. func (c *Action) GetBool(key string) (bool, error) {
  779. return strconv.ParseBool(c.GetString(key))
  780. }
  781. func (c *Action) GetFloat(key string) (float64, error) {
  782. return strconv.ParseFloat(c.GetString(key), 64)
  783. }
  784. func (c *Action) GetFile(key string) (multipart.File, *multipart.FileHeader, error) {
  785. return c.Request.FormFile(key)
  786. }
  787. /** 2017-01-18 多文件上传支持 wanghuidong **/
  788. func (c *Action) GetFiles() ([]*multipart.FileHeader, error) {
  789. c.Request.ParseMultipartForm(32 << 20)
  790. mp := c.Request.MultipartForm
  791. if mp == nil {
  792. log.Println("not MultipartForm.")
  793. return nil, nil
  794. }
  795. fileHeaderMap := mp.File
  796. fileHeaders := make([]*multipart.FileHeader, 0)
  797. for _, _fileHeaders := range fileHeaderMap {
  798. for _, fileHeader := range _fileHeaders {
  799. fileHeaders = append(fileHeaders, fileHeader)
  800. }
  801. }
  802. return fileHeaders, nil
  803. }
  804. func (c *Action) GetLogger() *log.Logger {
  805. return c.App.Logger
  806. }
  807. func (c *Action) SaveToFile(fromfile, tofile string) error {
  808. log.Println("fromfile--" + fromfile + "---tofile:" + tofile)
  809. file, _, err := c.Request.FormFile(fromfile)
  810. log.Println("file: ", file)
  811. if err != nil {
  812. return err
  813. }
  814. defer file.Close()
  815. f, err := os.OpenFile(tofile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
  816. if err != nil {
  817. return err
  818. }
  819. defer f.Close()
  820. _, err = io.Copy(f, file)
  821. return err
  822. }
  823. func (c *Action) Session() *httpsession.Session {
  824. if c.session == nil {
  825. c.session = c.App.SessionManager.Session(c.Request, c.ResponseWriter)
  826. }
  827. return c.session
  828. }
  829. func (c *Action) GetSession(key string) interface{} {
  830. return c.Session().Get(key)
  831. }
  832. func (c *Action) SetSession(key string, value interface{}) {
  833. c.Session().Set(key, value)
  834. }
  835. func (c *Action) DelSession(key string) {
  836. c.Session().Del(key)
  837. }
  838. func newInclude(c *Action, content string) string {
  839. for i := 0; i < 5; i++ {
  840. newcontent := regInclude.ReplaceAllStringFunc(content, func(m string) string {
  841. tpl := regInclude.FindStringSubmatch(m)[1]
  842. c, _ := c.getTemplate(tpl)
  843. return string(c)
  844. })
  845. if content == newcontent {
  846. break
  847. }
  848. content = newcontent
  849. }
  850. return content
  851. }