req.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. // The route pattern eg: /user
  33. func (req *Req) getPattern() string {
  34. _, pattern := rtr.Handler(req.r)
  35. return pattern
  36. }
  37. func (req *Req) Cookie(name string) (string, error) {
  38. cookie, err := req.r.Cookie(name)
  39. if err != nil {
  40. return "", err
  41. }
  42. return cookie.Value, nil
  43. }
  44. func (req *Req) getParentPath() string {
  45. parentPath := ""
  46. arr := strings.Split(req.Path, "/")
  47. for i := 0; i < len(arr)-1; i++ {
  48. if arr[i] == "" {
  49. continue
  50. }
  51. parentPath += "/" + arr[i]
  52. }
  53. return parentPath
  54. }