request.go 912 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package srv
  2. import (
  3. "net/http"
  4. "strings"
  5. )
  6. type Req struct {
  7. r *http.Request
  8. AppURL string
  9. Path string
  10. ParentPath string
  11. Pattern string
  12. Ctx map[string]any
  13. }
  14. func (req *Req) Construct(r *http.Request) {
  15. req.r = r
  16. req.AppURL = "/" + r.Host
  17. req.Path = r.RequestURI
  18. req.ParentPath = req.getParentPath()
  19. req.Pattern = req.getPattern()
  20. req.Ctx = make(map[string]any)
  21. }
  22. // The route pattern eg: /user
  23. func (req *Req) getPattern() string {
  24. _, pattern := router.Handler(req.r)
  25. return pattern
  26. }
  27. func (req *Req) Cookie(name string) (string, error) {
  28. cookie, err := req.r.Cookie(name)
  29. if err != nil {
  30. return "", err
  31. }
  32. return cookie.Value, nil
  33. }
  34. func (req *Req) getParentPath() string {
  35. parentPath := ""
  36. arr := strings.Split(req.Path, "/")
  37. for i := 0; i < len(arr)-1; i++ {
  38. if arr[i] == "" {
  39. continue
  40. }
  41. parentPath += "/" + arr[i]
  42. }
  43. return parentPath
  44. }