context.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. "net/http"
  7. "github.com/codegangsta/martini"
  8. "github.com/martini-contrib/render"
  9. "github.com/martini-contrib/sessions"
  10. "github.com/gogits/gogs/models"
  11. "github.com/gogits/gogs/modules/auth"
  12. "github.com/gogits/gogs/modules/base"
  13. "github.com/gogits/gogs/modules/log"
  14. )
  15. type Context struct {
  16. c martini.Context
  17. p martini.Params
  18. Req *http.Request
  19. Res http.ResponseWriter
  20. Session sessions.Session
  21. Data base.TmplData
  22. Render render.Render
  23. User *models.User
  24. IsSigned bool
  25. }
  26. func (ctx *Context) Query(name string) string {
  27. ctx.Req.ParseForm()
  28. return ctx.Req.Form.Get(name)
  29. }
  30. // func (ctx *Context) Param(name string) string {
  31. // return ctx.p[name]
  32. // }
  33. func (ctx *Context) Log(status int, title string, err error) {
  34. log.Handle(status, title, ctx.Data, ctx.Render, err)
  35. }
  36. func InitContext() martini.Handler {
  37. return func(res http.ResponseWriter, r *http.Request, c martini.Context,
  38. session sessions.Session, rd render.Render) {
  39. data := base.TmplData{}
  40. ctx := &Context{
  41. c: c,
  42. // p: p,
  43. Req: r,
  44. Res: res,
  45. Data: data,
  46. Render: rd,
  47. }
  48. // Get user from session if logined.
  49. user := auth.SignedInUser(session)
  50. ctx.User = user
  51. ctx.IsSigned = ctx != nil
  52. data["IsSigned"] = true
  53. data["SignedUser"] = user
  54. data["SignedUserId"] = user.Id
  55. data["SignedUserName"] = user.LowerName
  56. c.Map(ctx)
  57. c.Map(data)
  58. c.Next()
  59. }
  60. }