context.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. Session: session,
  53. Data: data,
  54. Render: rd,
  55. }
  56. // Get user from session if logined.
  57. user := auth.SignedInUser(session)
  58. ctx.User = user
  59. ctx.IsSigned = user != nil
  60. data["IsSigned"] = ctx.IsSigned
  61. if user != nil {
  62. data["SignedUser"] = user
  63. data["SignedUserId"] = user.Id
  64. data["SignedUserName"] = user.LowerName
  65. }
  66. c.Map(ctx)
  67. c.Map(data)
  68. c.Next()
  69. }
  70. }