context.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package middleware
  5. import (
  6. "fmt"
  7. "net/http"
  8. "github.com/codegangsta/martini"
  9. "github.com/martini-contrib/render"
  10. "github.com/martini-contrib/sessions"
  11. "github.com/gogits/gogs/models"
  12. "github.com/gogits/gogs/modules/auth"
  13. "github.com/gogits/gogs/modules/base"
  14. "github.com/gogits/gogs/modules/log"
  15. )
  16. // Context represents context of a request.
  17. type Context struct {
  18. c martini.Context
  19. p martini.Params
  20. Req *http.Request
  21. Res http.ResponseWriter
  22. Session sessions.Session
  23. Data base.TmplData
  24. Render render.Render
  25. User *models.User
  26. IsSigned bool
  27. }
  28. // Query querys form parameter.
  29. func (ctx *Context) Query(name string) string {
  30. ctx.Req.ParseForm()
  31. return ctx.Req.Form.Get(name)
  32. }
  33. // func (ctx *Context) Param(name string) string {
  34. // return ctx.p[name]
  35. // }
  36. // Handle handles and logs error by given status.
  37. func (ctx *Context) Handle(status int, title string, err error) {
  38. ctx.Data["ErrorMsg"] = err
  39. log.Error("%s: %v", title, err)
  40. ctx.Render.HTML(status, fmt.Sprintf("status/%d", status), ctx.Data)
  41. }
  42. // InitContext initializes a classic context for a request.
  43. func InitContext() martini.Handler {
  44. return func(res http.ResponseWriter, r *http.Request, c martini.Context,
  45. session sessions.Session, rd render.Render) {
  46. data := base.TmplData{}
  47. ctx := &Context{
  48. c: c,
  49. // p: p,
  50. Req: r,
  51. Res: res,
  52. Data: data,
  53. Render: rd,
  54. }
  55. // Get user from session if logined.
  56. user := auth.SignedInUser(session)
  57. ctx.User = user
  58. ctx.IsSigned = user != nil
  59. data["IsSigned"] = ctx.IsSigned
  60. if user != nil {
  61. data["SignedUser"] = user
  62. data["SignedUserId"] = user.Id
  63. data["SignedUserName"] = user.LowerName
  64. }
  65. c.Map(ctx)
  66. c.Map(data)
  67. c.Next()
  68. }
  69. }