req.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. r.ParseForm()
  16. req.r = r
  17. req.AppURL = "/" + r.Host
  18. req.Path = r.RequestURI
  19. req.ParentPath = req.getParentPath()
  20. req.Pattern = req.getPattern()
  21. req.Ctx = make(map[string]any)
  22. }
  23. func (req *Req) Body(key string) string {
  24. return req.r.FormValue(key)
  25. }
  26. func (req *Req) Query(key string) string {
  27. return req.r.URL.Query().Get(key)
  28. }
  29. func (req *Req) Param(key string) string {
  30. return req.r.PathValue(key)
  31. }
  32. func (req *Req) Cookie(name string) (string, error) {
  33. cookie, err := req.r.Cookie(name)
  34. if err != nil {
  35. return "", err
  36. }
  37. return cookie.Value, nil
  38. }
  39. func (req *Req) getParentPath() string {
  40. parentPath := ""
  41. arr := strings.Split(req.Path, "/")
  42. for i := 0; i < len(arr)-1; i++ {
  43. if arr[i] == "" {
  44. continue
  45. }
  46. parentPath += "/" + arr[i]
  47. }
  48. return parentPath
  49. }
  50. func (req *Req) getPattern() string {
  51. _, pattern := rtr.Handler(req.r)
  52. return pattern
  53. }