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.
 
 
 

76 lines
1.6 KiB

  1. package handlers
  2. import (
  3. "net/http"
  4. )
  5. // Interface giving easy access to the most common augmented features.
  6. type GhostWriter interface {
  7. http.ResponseWriter
  8. UserName() string
  9. User() interface{}
  10. Context() map[interface{}]interface{}
  11. Session() *Session
  12. }
  13. // Internal implementation of the GhostWriter interface.
  14. type ghostWriter struct {
  15. http.ResponseWriter
  16. userName string
  17. user interface{}
  18. ctx map[interface{}]interface{}
  19. ssn *Session
  20. }
  21. func (this *ghostWriter) UserName() string {
  22. return this.userName
  23. }
  24. func (this *ghostWriter) User() interface{} {
  25. return this.user
  26. }
  27. func (this *ghostWriter) Context() map[interface{}]interface{} {
  28. return this.ctx
  29. }
  30. func (this *ghostWriter) Session() *Session {
  31. return this.ssn
  32. }
  33. // Convenience handler that wraps a custom function with direct access to the
  34. // authenticated user, context and session on the writer.
  35. func GhostHandlerFunc(h func(w GhostWriter, r *http.Request)) http.HandlerFunc {
  36. return func(w http.ResponseWriter, r *http.Request) {
  37. if gw, ok := getGhostWriter(w); ok {
  38. // Self-awareness
  39. h(gw, r)
  40. return
  41. }
  42. uid, _ := GetUserName(w)
  43. usr, _ := GetUser(w)
  44. ctx, _ := GetContext(w)
  45. ssn, _ := GetSession(w)
  46. gw := &ghostWriter{
  47. w,
  48. uid,
  49. usr,
  50. ctx,
  51. ssn,
  52. }
  53. h(gw, r)
  54. }
  55. }
  56. // Check the writer chain to find a ghostWriter.
  57. func getGhostWriter(w http.ResponseWriter) (*ghostWriter, bool) {
  58. gw, ok := GetResponseWriter(w, func(tst http.ResponseWriter) bool {
  59. _, ok := tst.(*ghostWriter)
  60. return ok
  61. })
  62. if ok {
  63. return gw.(*ghostWriter), true
  64. }
  65. return nil, false
  66. }