You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

context.go 14 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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/go-macaron/inject"
  32. "github.com/unknwon/com"
  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 renders the HTML with default template set.
  143. func (ctx *Context) HTML(status int, name string, data ...interface{}) {
  144. ctx.renderHTML(status, DEFAULT_TPL_SET_NAME, name, data...)
  145. }
  146. // HTMLSet renders the HTML with given template set name.
  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. // AllParams returns all params.
  224. func (ctx *Context) AllParams() Params {
  225. return ctx.params
  226. }
  227. // SetParams sets value of param with given name.
  228. func (ctx *Context) SetParams(name, val string) {
  229. if name != "*" && !strings.HasPrefix(name, ":") {
  230. name = ":" + name
  231. }
  232. ctx.params[name] = val
  233. }
  234. // ReplaceAllParams replace all current params with given params
  235. func (ctx *Context) ReplaceAllParams(params Params) {
  236. ctx.params = params
  237. }
  238. // ParamsEscape returns escapred params result.
  239. // e.g. ctx.ParamsEscape(":uname")
  240. func (ctx *Context) ParamsEscape(name string) string {
  241. return template.HTMLEscapeString(ctx.Params(name))
  242. }
  243. // ParamsInt returns params result in int type.
  244. // e.g. ctx.ParamsInt(":uid")
  245. func (ctx *Context) ParamsInt(name string) int {
  246. return com.StrTo(ctx.Params(name)).MustInt()
  247. }
  248. // ParamsInt64 returns params result in int64 type.
  249. // e.g. ctx.ParamsInt64(":uid")
  250. func (ctx *Context) ParamsInt64(name string) int64 {
  251. return com.StrTo(ctx.Params(name)).MustInt64()
  252. }
  253. // ParamsFloat64 returns params result in int64 type.
  254. // e.g. ctx.ParamsFloat64(":uid")
  255. func (ctx *Context) ParamsFloat64(name string) float64 {
  256. v, _ := strconv.ParseFloat(ctx.Params(name), 64)
  257. return v
  258. }
  259. // GetFile returns information about user upload file by given form field name.
  260. func (ctx *Context) GetFile(name string) (multipart.File, *multipart.FileHeader, error) {
  261. return ctx.Req.FormFile(name)
  262. }
  263. // SaveToFile reads a file from request by field name and saves to given path.
  264. func (ctx *Context) SaveToFile(name, savePath string) error {
  265. fr, _, err := ctx.GetFile(name)
  266. if err != nil {
  267. return err
  268. }
  269. defer fr.Close()
  270. fw, err := os.OpenFile(savePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
  271. if err != nil {
  272. return err
  273. }
  274. defer fw.Close()
  275. _, err = io.Copy(fw, fr)
  276. return err
  277. }
  278. // SetCookie sets given cookie value to response header.
  279. // FIXME: IE support? http://golanghome.com/post/620#reply2
  280. func (ctx *Context) SetCookie(name string, value string, others ...interface{}) {
  281. cookie := http.Cookie{}
  282. cookie.Name = name
  283. cookie.Value = url.QueryEscape(value)
  284. if len(others) > 0 {
  285. switch v := others[0].(type) {
  286. case int:
  287. cookie.MaxAge = v
  288. case int64:
  289. cookie.MaxAge = int(v)
  290. case int32:
  291. cookie.MaxAge = int(v)
  292. }
  293. }
  294. cookie.Path = "/"
  295. if len(others) > 1 {
  296. if v, ok := others[1].(string); ok && len(v) > 0 {
  297. cookie.Path = v
  298. }
  299. }
  300. if len(others) > 2 {
  301. if v, ok := others[2].(string); ok && len(v) > 0 {
  302. cookie.Domain = v
  303. }
  304. }
  305. if len(others) > 3 {
  306. switch v := others[3].(type) {
  307. case bool:
  308. cookie.Secure = v
  309. default:
  310. if others[3] != nil {
  311. cookie.Secure = true
  312. }
  313. }
  314. }
  315. if len(others) > 4 {
  316. if v, ok := others[4].(bool); ok && v {
  317. cookie.HttpOnly = true
  318. }
  319. }
  320. if len(others) > 5 {
  321. if v, ok := others[5].(time.Time); ok {
  322. cookie.Expires = v
  323. cookie.RawExpires = v.Format(time.UnixDate)
  324. }
  325. }
  326. ctx.Resp.Header().Add("Set-Cookie", cookie.String())
  327. }
  328. // GetCookie returns given cookie value from request header.
  329. func (ctx *Context) GetCookie(name string) string {
  330. cookie, err := ctx.Req.Cookie(name)
  331. if err != nil {
  332. return ""
  333. }
  334. val, _ := url.QueryUnescape(cookie.Value)
  335. return val
  336. }
  337. // GetCookieInt returns cookie result in int type.
  338. func (ctx *Context) GetCookieInt(name string) int {
  339. return com.StrTo(ctx.GetCookie(name)).MustInt()
  340. }
  341. // GetCookieInt64 returns cookie result in int64 type.
  342. func (ctx *Context) GetCookieInt64(name string) int64 {
  343. return com.StrTo(ctx.GetCookie(name)).MustInt64()
  344. }
  345. // GetCookieFloat64 returns cookie result in float64 type.
  346. func (ctx *Context) GetCookieFloat64(name string) float64 {
  347. v, _ := strconv.ParseFloat(ctx.GetCookie(name), 64)
  348. return v
  349. }
  350. var defaultCookieSecret string
  351. // SetDefaultCookieSecret sets global default secure cookie secret.
  352. func (m *Macaron) SetDefaultCookieSecret(secret string) {
  353. defaultCookieSecret = secret
  354. }
  355. // SetSecureCookie sets given cookie value to response header with default secret string.
  356. func (ctx *Context) SetSecureCookie(name, value string, others ...interface{}) {
  357. ctx.SetSuperSecureCookie(defaultCookieSecret, name, value, others...)
  358. }
  359. // GetSecureCookie returns given cookie value from request header with default secret string.
  360. func (ctx *Context) GetSecureCookie(key string) (string, bool) {
  361. return ctx.GetSuperSecureCookie(defaultCookieSecret, key)
  362. }
  363. // SetSuperSecureCookie sets given cookie value to response header with secret string.
  364. func (ctx *Context) SetSuperSecureCookie(secret, name, value string, others ...interface{}) {
  365. key := pbkdf2.Key([]byte(secret), []byte(secret), 1000, 16, sha256.New)
  366. text, err := com.AESGCMEncrypt(key, []byte(value))
  367. if err != nil {
  368. panic("error encrypting cookie: " + err.Error())
  369. }
  370. ctx.SetCookie(name, hex.EncodeToString(text), others...)
  371. }
  372. // GetSuperSecureCookie returns given cookie value from request header with secret string.
  373. func (ctx *Context) GetSuperSecureCookie(secret, name string) (string, bool) {
  374. val := ctx.GetCookie(name)
  375. if val == "" {
  376. return "", false
  377. }
  378. text, err := hex.DecodeString(val)
  379. if err != nil {
  380. return "", false
  381. }
  382. key := pbkdf2.Key([]byte(secret), []byte(secret), 1000, 16, sha256.New)
  383. text, err = com.AESGCMDecrypt(key, text)
  384. return string(text), err == nil
  385. }
  386. func (ctx *Context) setRawContentHeader() {
  387. ctx.Resp.Header().Set("Content-Description", "Raw content")
  388. ctx.Resp.Header().Set("Content-Type", "text/plain")
  389. ctx.Resp.Header().Set("Expires", "0")
  390. ctx.Resp.Header().Set("Cache-Control", "must-revalidate")
  391. ctx.Resp.Header().Set("Pragma", "public")
  392. }
  393. // ServeContent serves given content to response.
  394. func (ctx *Context) ServeContent(name string, r io.ReadSeeker, params ...interface{}) {
  395. modtime := time.Now()
  396. for _, p := range params {
  397. switch v := p.(type) {
  398. case time.Time:
  399. modtime = v
  400. }
  401. }
  402. ctx.setRawContentHeader()
  403. http.ServeContent(ctx.Resp, ctx.Req.Request, name, modtime, r)
  404. }
  405. // ServeFileContent serves given file as content to response.
  406. func (ctx *Context) ServeFileContent(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. f, err := os.Open(file)
  414. if err != nil {
  415. if Env == PROD {
  416. http.Error(ctx.Resp, "Internal Server Error", 500)
  417. } else {
  418. http.Error(ctx.Resp, err.Error(), 500)
  419. }
  420. return
  421. }
  422. defer f.Close()
  423. ctx.setRawContentHeader()
  424. http.ServeContent(ctx.Resp, ctx.Req.Request, name, time.Now(), f)
  425. }
  426. // ServeFile serves given file to response.
  427. func (ctx *Context) ServeFile(file string, names ...string) {
  428. var name string
  429. if len(names) > 0 {
  430. name = names[0]
  431. } else {
  432. name = path.Base(file)
  433. }
  434. ctx.Resp.Header().Set("Content-Description", "File Transfer")
  435. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  436. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+name)
  437. ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary")
  438. ctx.Resp.Header().Set("Expires", "0")
  439. ctx.Resp.Header().Set("Cache-Control", "must-revalidate")
  440. ctx.Resp.Header().Set("Pragma", "public")
  441. http.ServeFile(ctx.Resp, ctx.Req.Request, file)
  442. }
  443. // ChangeStaticPath changes static path from old to new one.
  444. func (ctx *Context) ChangeStaticPath(oldPath, newPath string) {
  445. if !filepath.IsAbs(oldPath) {
  446. oldPath = filepath.Join(Root, oldPath)
  447. }
  448. dir := statics.Get(oldPath)
  449. if dir != nil {
  450. statics.Delete(oldPath)
  451. if !filepath.IsAbs(newPath) {
  452. newPath = filepath.Join(Root, newPath)
  453. }
  454. *dir = http.Dir(newPath)
  455. statics.Set(dir)
  456. }
  457. }