context.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. // Copyright 2014 The Macaron Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License"): you may
  4. // not use this file except in compliance with the License. You may obtain
  5. // a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  11. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  12. // License for the specific language governing permissions and limitations
  13. // under the License.
  14. package macaron
  15. import (
  16. "crypto/md5"
  17. "encoding/hex"
  18. "html/template"
  19. "io"
  20. "io/ioutil"
  21. "mime/multipart"
  22. "net/http"
  23. "net/url"
  24. "os"
  25. "path"
  26. "path/filepath"
  27. "reflect"
  28. "strconv"
  29. "strings"
  30. "time"
  31. "github.com/Unknwon/com"
  32. "github.com/go-macaron/inject"
  33. )
  34. // Locale reprents a localization interface.
  35. type Locale interface {
  36. Language() string
  37. Tr(string, ...interface{}) string
  38. }
  39. // RequestBody represents a request body.
  40. type RequestBody struct {
  41. reader io.ReadCloser
  42. }
  43. // Bytes reads and returns content of request body in bytes.
  44. func (rb *RequestBody) Bytes() ([]byte, error) {
  45. return ioutil.ReadAll(rb.reader)
  46. }
  47. // String reads and returns content of request body in string.
  48. func (rb *RequestBody) String() (string, error) {
  49. data, err := rb.Bytes()
  50. return string(data), err
  51. }
  52. // ReadCloser returns a ReadCloser for request body.
  53. func (rb *RequestBody) ReadCloser() io.ReadCloser {
  54. return rb.reader
  55. }
  56. // Request represents an HTTP request received by a server or to be sent by a client.
  57. type Request struct {
  58. *http.Request
  59. }
  60. func (r *Request) Body() *RequestBody {
  61. return &RequestBody{r.Request.Body}
  62. }
  63. // Context represents the runtime context of current request of Macaron instance.
  64. // It is the integration of most frequently used middlewares and helper methods.
  65. type Context struct {
  66. inject.Injector
  67. handlers []Handler
  68. action Handler
  69. index int
  70. *Router
  71. Req Request
  72. Resp ResponseWriter
  73. params Params
  74. Render // Not nil only if you use macaran.Render middleware.
  75. Locale
  76. Data map[string]interface{}
  77. }
  78. func (c *Context) handler() Handler {
  79. if c.index < len(c.handlers) {
  80. return c.handlers[c.index]
  81. }
  82. if c.index == len(c.handlers) {
  83. return c.action
  84. }
  85. panic("invalid index for context handler")
  86. }
  87. func (c *Context) Next() {
  88. c.index += 1
  89. c.run()
  90. }
  91. func (c *Context) Written() bool {
  92. return c.Resp.Written()
  93. }
  94. func (c *Context) run() {
  95. for c.index <= len(c.handlers) {
  96. vals, err := c.Invoke(c.handler())
  97. if err != nil {
  98. panic(err)
  99. }
  100. c.index += 1
  101. // if the handler returned something, write it to the http response
  102. if len(vals) > 0 {
  103. ev := c.GetVal(reflect.TypeOf(ReturnHandler(nil)))
  104. handleReturn := ev.Interface().(ReturnHandler)
  105. handleReturn(c, vals)
  106. }
  107. if c.Written() {
  108. return
  109. }
  110. }
  111. }
  112. // RemoteAddr returns more real IP address.
  113. func (ctx *Context) RemoteAddr() string {
  114. addr := ctx.Req.Header.Get("X-Real-IP")
  115. if len(addr) == 0 {
  116. addr = ctx.Req.Header.Get("X-Forwarded-For")
  117. if addr == "" {
  118. addr = ctx.Req.RemoteAddr
  119. if i := strings.LastIndex(addr, ":"); i > -1 {
  120. addr = addr[:i]
  121. }
  122. }
  123. }
  124. return addr
  125. }
  126. func (ctx *Context) renderHTML(status int, setName, tplName string, data ...interface{}) {
  127. if ctx.Render == nil {
  128. panic("renderer middleware hasn't been registered")
  129. }
  130. if len(data) <= 0 {
  131. ctx.Render.HTMLSet(status, setName, tplName, ctx.Data)
  132. } else if len(data) == 1 {
  133. ctx.Render.HTMLSet(status, setName, tplName, data[0])
  134. } else {
  135. ctx.Render.HTMLSet(status, setName, tplName, data[0], data[1].(HTMLOptions))
  136. }
  137. }
  138. // HTML calls Render.HTML but allows less arguments.
  139. func (ctx *Context) HTML(status int, name string, data ...interface{}) {
  140. ctx.renderHTML(status, _DEFAULT_TPL_SET_NAME, name, data...)
  141. }
  142. // HTML calls Render.HTMLSet but allows less arguments.
  143. func (ctx *Context) HTMLSet(status int, setName, tplName string, data ...interface{}) {
  144. ctx.renderHTML(status, setName, tplName, data...)
  145. }
  146. func (ctx *Context) Redirect(location string, status ...int) {
  147. code := http.StatusFound
  148. if len(status) == 1 {
  149. code = status[0]
  150. }
  151. http.Redirect(ctx.Resp, ctx.Req.Request, location, code)
  152. }
  153. // Maximum amount of memory to use when parsing a multipart form.
  154. // Set this to whatever value you prefer; default is 10 MB.
  155. var MaxMemory = int64(1024 * 1024 * 10)
  156. func (ctx *Context) parseForm() {
  157. if ctx.Req.Form != nil {
  158. return
  159. }
  160. contentType := ctx.Req.Header.Get(_CONTENT_TYPE)
  161. if (ctx.Req.Method == "POST" || ctx.Req.Method == "PUT") &&
  162. len(contentType) > 0 && strings.Contains(contentType, "multipart/form-data") {
  163. ctx.Req.ParseMultipartForm(MaxMemory)
  164. } else {
  165. ctx.Req.ParseForm()
  166. }
  167. }
  168. // Query querys form parameter.
  169. func (ctx *Context) Query(name string) string {
  170. ctx.parseForm()
  171. return ctx.Req.Form.Get(name)
  172. }
  173. // QueryTrim querys and trims spaces form parameter.
  174. func (ctx *Context) QueryTrim(name string) string {
  175. return strings.TrimSpace(ctx.Query(name))
  176. }
  177. // QueryStrings returns a list of results by given query name.
  178. func (ctx *Context) QueryStrings(name string) []string {
  179. ctx.parseForm()
  180. vals, ok := ctx.Req.Form[name]
  181. if !ok {
  182. return []string{}
  183. }
  184. return vals
  185. }
  186. // QueryEscape returns escapred query result.
  187. func (ctx *Context) QueryEscape(name string) string {
  188. return template.HTMLEscapeString(ctx.Query(name))
  189. }
  190. // QueryInt returns query result in int type.
  191. func (ctx *Context) QueryInt(name string) int {
  192. return com.StrTo(ctx.Query(name)).MustInt()
  193. }
  194. // QueryInt64 returns query result in int64 type.
  195. func (ctx *Context) QueryInt64(name string) int64 {
  196. return com.StrTo(ctx.Query(name)).MustInt64()
  197. }
  198. // QueryFloat64 returns query result in float64 type.
  199. func (ctx *Context) QueryFloat64(name string) float64 {
  200. v, _ := strconv.ParseFloat(ctx.Query(name), 64)
  201. return v
  202. }
  203. // Params returns value of given param name.
  204. // e.g. ctx.Params(":uid") or ctx.Params("uid")
  205. func (ctx *Context) Params(name string) string {
  206. if len(name) == 0 {
  207. return ""
  208. }
  209. if len(name) > 1 && name[0] != ':' {
  210. name = ":" + name
  211. }
  212. return ctx.params[name]
  213. }
  214. // SetParams sets value of param with given name.
  215. func (ctx *Context) SetParams(name, val string) {
  216. if !strings.HasPrefix(name, ":") {
  217. name = ":" + name
  218. }
  219. ctx.params[name] = val
  220. }
  221. // ParamsEscape returns escapred params result.
  222. // e.g. ctx.ParamsEscape(":uname")
  223. func (ctx *Context) ParamsEscape(name string) string {
  224. return template.HTMLEscapeString(ctx.Params(name))
  225. }
  226. // ParamsInt returns params result in int type.
  227. // e.g. ctx.ParamsInt(":uid")
  228. func (ctx *Context) ParamsInt(name string) int {
  229. return com.StrTo(ctx.Params(name)).MustInt()
  230. }
  231. // ParamsInt64 returns params result in int64 type.
  232. // e.g. ctx.ParamsInt64(":uid")
  233. func (ctx *Context) ParamsInt64(name string) int64 {
  234. return com.StrTo(ctx.Params(name)).MustInt64()
  235. }
  236. // ParamsFloat64 returns params result in int64 type.
  237. // e.g. ctx.ParamsFloat64(":uid")
  238. func (ctx *Context) ParamsFloat64(name string) float64 {
  239. v, _ := strconv.ParseFloat(ctx.Params(name), 64)
  240. return v
  241. }
  242. // GetFile returns information about user upload file by given form field name.
  243. func (ctx *Context) GetFile(name string) (multipart.File, *multipart.FileHeader, error) {
  244. return ctx.Req.FormFile(name)
  245. }
  246. // SaveToFile reads a file from request by field name and saves to given path.
  247. func (ctx *Context) SaveToFile(name, savePath string) error {
  248. fr, _, err := ctx.GetFile(name)
  249. if err != nil {
  250. return err
  251. }
  252. defer fr.Close()
  253. fw, err := os.OpenFile(savePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
  254. if err != nil {
  255. return err
  256. }
  257. defer fw.Close()
  258. _, err = io.Copy(fw, fr)
  259. return err
  260. }
  261. // SetCookie sets given cookie value to response header.
  262. // FIXME: IE support? http://golanghome.com/post/620#reply2
  263. func (ctx *Context) SetCookie(name string, value string, others ...interface{}) {
  264. cookie := http.Cookie{}
  265. cookie.Name = name
  266. cookie.Value = url.QueryEscape(value)
  267. if len(others) > 0 {
  268. switch v := others[0].(type) {
  269. case int:
  270. cookie.MaxAge = v
  271. case int64:
  272. cookie.MaxAge = int(v)
  273. case int32:
  274. cookie.MaxAge = int(v)
  275. }
  276. }
  277. cookie.Path = "/"
  278. if len(others) > 1 {
  279. if v, ok := others[1].(string); ok && len(v) > 0 {
  280. cookie.Path = v
  281. }
  282. }
  283. if len(others) > 2 {
  284. if v, ok := others[2].(string); ok && len(v) > 0 {
  285. cookie.Domain = v
  286. }
  287. }
  288. if len(others) > 3 {
  289. switch v := others[3].(type) {
  290. case bool:
  291. cookie.Secure = v
  292. default:
  293. if others[3] != nil {
  294. cookie.Secure = true
  295. }
  296. }
  297. }
  298. if len(others) > 4 {
  299. if v, ok := others[4].(bool); ok && v {
  300. cookie.HttpOnly = true
  301. }
  302. }
  303. ctx.Resp.Header().Add("Set-Cookie", cookie.String())
  304. }
  305. // GetCookie returns given cookie value from request header.
  306. func (ctx *Context) GetCookie(name string) string {
  307. cookie, err := ctx.Req.Cookie(name)
  308. if err != nil {
  309. return ""
  310. }
  311. val, _ := url.QueryUnescape(cookie.Value)
  312. return val
  313. }
  314. // GetCookieInt returns cookie result in int type.
  315. func (ctx *Context) GetCookieInt(name string) int {
  316. return com.StrTo(ctx.GetCookie(name)).MustInt()
  317. }
  318. // GetCookieInt64 returns cookie result in int64 type.
  319. func (ctx *Context) GetCookieInt64(name string) int64 {
  320. return com.StrTo(ctx.GetCookie(name)).MustInt64()
  321. }
  322. // GetCookieFloat64 returns cookie result in float64 type.
  323. func (ctx *Context) GetCookieFloat64(name string) float64 {
  324. v, _ := strconv.ParseFloat(ctx.GetCookie(name), 64)
  325. return v
  326. }
  327. var defaultCookieSecret string
  328. // SetDefaultCookieSecret sets global default secure cookie secret.
  329. func (m *Macaron) SetDefaultCookieSecret(secret string) {
  330. defaultCookieSecret = secret
  331. }
  332. // SetSecureCookie sets given cookie value to response header with default secret string.
  333. func (ctx *Context) SetSecureCookie(name, value string, others ...interface{}) {
  334. ctx.SetSuperSecureCookie(defaultCookieSecret, name, value, others...)
  335. }
  336. // GetSecureCookie returns given cookie value from request header with default secret string.
  337. func (ctx *Context) GetSecureCookie(key string) (string, bool) {
  338. return ctx.GetSuperSecureCookie(defaultCookieSecret, key)
  339. }
  340. // SetSuperSecureCookie sets given cookie value to response header with secret string.
  341. func (ctx *Context) SetSuperSecureCookie(secret, name, value string, others ...interface{}) {
  342. m := md5.Sum([]byte(secret))
  343. secret = hex.EncodeToString(m[:])
  344. text, err := com.AESEncrypt([]byte(secret), []byte(value))
  345. if err != nil {
  346. panic("error encrypting cookie: " + err.Error())
  347. }
  348. ctx.SetCookie(name, hex.EncodeToString(text), others...)
  349. }
  350. // GetSuperSecureCookie returns given cookie value from request header with secret string.
  351. func (ctx *Context) GetSuperSecureCookie(secret, key string) (string, bool) {
  352. val := ctx.GetCookie(key)
  353. if val == "" {
  354. return "", false
  355. }
  356. data, err := hex.DecodeString(val)
  357. if err != nil {
  358. return "", false
  359. }
  360. m := md5.Sum([]byte(secret))
  361. secret = hex.EncodeToString(m[:])
  362. text, err := com.AESDecrypt([]byte(secret), data)
  363. return string(text), err == nil
  364. }
  365. func (ctx *Context) setRawContentHeader() {
  366. ctx.Resp.Header().Set("Content-Description", "Raw content")
  367. ctx.Resp.Header().Set("Content-Type", "text/plain")
  368. ctx.Resp.Header().Set("Expires", "0")
  369. ctx.Resp.Header().Set("Cache-Control", "must-revalidate")
  370. ctx.Resp.Header().Set("Pragma", "public")
  371. }
  372. // ServeContent serves given content to response.
  373. func (ctx *Context) ServeContent(name string, r io.ReadSeeker, params ...interface{}) {
  374. modtime := time.Now()
  375. for _, p := range params {
  376. switch v := p.(type) {
  377. case time.Time:
  378. modtime = v
  379. }
  380. }
  381. ctx.setRawContentHeader()
  382. http.ServeContent(ctx.Resp, ctx.Req.Request, name, modtime, r)
  383. }
  384. // ServeFileContent serves given file as content to response.
  385. func (ctx *Context) ServeFileContent(file string, names ...string) {
  386. var name string
  387. if len(names) > 0 {
  388. name = names[0]
  389. } else {
  390. name = path.Base(file)
  391. }
  392. f, err := os.Open(file)
  393. if err != nil {
  394. if Env == PROD {
  395. http.Error(ctx.Resp, "Internal Server Error", 500)
  396. } else {
  397. http.Error(ctx.Resp, err.Error(), 500)
  398. }
  399. return
  400. }
  401. defer f.Close()
  402. ctx.setRawContentHeader()
  403. http.ServeContent(ctx.Resp, ctx.Req.Request, name, time.Now(), f)
  404. }
  405. // ServeFile serves given file to response.
  406. func (ctx *Context) ServeFile(file string, names ...string) {
  407. var name string
  408. if len(names) > 0 {
  409. name = names[0]
  410. } else {
  411. name = path.Base(file)
  412. }
  413. ctx.Resp.Header().Set("Content-Description", "File Transfer")
  414. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  415. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+name)
  416. ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary")
  417. ctx.Resp.Header().Set("Expires", "0")
  418. ctx.Resp.Header().Set("Cache-Control", "must-revalidate")
  419. ctx.Resp.Header().Set("Pragma", "public")
  420. http.ServeFile(ctx.Resp, ctx.Req.Request, file)
  421. }
  422. // ChangeStaticPath changes static path from old to new one.
  423. func (ctx *Context) ChangeStaticPath(oldPath, newPath string) {
  424. if !filepath.IsAbs(oldPath) {
  425. oldPath = filepath.Join(Root, oldPath)
  426. }
  427. dir := statics.Get(oldPath)
  428. if dir != nil {
  429. statics.Delete(oldPath)
  430. if !filepath.IsAbs(newPath) {
  431. newPath = filepath.Join(Root, newPath)
  432. }
  433. *dir = http.Dir(newPath)
  434. statics.Set(dir)
  435. }
  436. }