context.go 13 KB

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