req.go 1.3 KB

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