action.go 24 KB

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