A web blog and personal homepage engine written in Go.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

89 lines
2.1 KiB

  1. package responses
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "net/url"
  7. "time"
  8. "git.kirsle.net/apps/gophertype/pkg/authentication"
  9. "git.kirsle.net/apps/gophertype/pkg/models"
  10. "git.kirsle.net/apps/gophertype/pkg/session"
  11. "git.kirsle.net/apps/gophertype/pkg/settings"
  12. "github.com/gorilla/sessions"
  13. )
  14. // NewTemplateVars creates the TemplateVars for your current request.
  15. func NewTemplateVars(w io.Writer, r *http.Request) TemplateValues {
  16. var s = settings.Current
  17. user, _ := authentication.CurrentUser(r)
  18. ses := session.Get(r)
  19. v := TemplateValues{
  20. SetupNeeded: !s.Initialized,
  21. Title: s.Title,
  22. Description: s.Description,
  23. Request: r,
  24. RequestTime: time.Now(),
  25. RequestDuration: time.Duration(0),
  26. Session: ses,
  27. Path: r.URL.Path,
  28. LoggedIn: authentication.LoggedIn(r),
  29. IsAdmin: user.IsAdmin,
  30. CurrentUser: user,
  31. V: map[string]interface{}{},
  32. }
  33. if rw, ok := w.(http.ResponseWriter); ok {
  34. v.ResponseWriter = rw
  35. v.Flashes = session.GetFlashes(rw, r)
  36. }
  37. return v
  38. }
  39. // TemplateValues holds the context for html templates.
  40. type TemplateValues struct {
  41. // When the site needs the initial config.
  42. SetupNeeded bool
  43. // Config values available as template variables.
  44. Title string
  45. Description string
  46. // Request variables
  47. Request *http.Request
  48. RequestTime time.Time
  49. RequestDuration time.Duration
  50. ResponseWriter http.ResponseWriter
  51. FormValues url.Values
  52. Path string // request path
  53. TemplatePath string // file path of html template, like "_builtin/error.gohtml"
  54. // Session variables
  55. Session *sessions.Session
  56. LoggedIn bool
  57. IsAdmin bool
  58. CurrentUser models.User
  59. // Common template variables.
  60. Message string
  61. Error interface{}
  62. ValidationError map[string][]string // form validation errors
  63. Flashes []string
  64. // Arbitrary controller-specific fields go in V.
  65. V map[string]interface{}
  66. }
  67. // Flash adds a message to flash on the next template render.
  68. func (v *TemplateValues) Flash(msg string, args ...interface{}) {
  69. v.Flashes = append(v.Flashes, fmt.Sprintf(msg, args...))
  70. }