12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- package srv
- import (
- "net/http"
- "strings"
- )
- type Req struct {
- r *http.Request
- AppURL string
- Path string
- ParentPath string
- Pattern string
- Ctx map[string]any
- }
- func (req *Req) Construct(r *http.Request) {
- r.ParseForm()
- req.r = r
- req.AppURL = "/" + r.Host
- req.Path = r.RequestURI
- req.ParentPath = req.getParentPath()
- req.Pattern = req.getPattern()
- req.Ctx = make(map[string]any)
- }
- func (req *Req) Body(key string) string {
- return req.r.FormValue(key)
- }
- func (req *Req) Query(key string) string {
- return req.r.URL.Query().Get(key)
- }
- func (req *Req) Param(key string) string {
- return req.r.PathValue(key)
- }
- // The route pattern eg: /user
- func (req *Req) getPattern() string {
- _, pattern := rtr.Handler(req.r)
- return pattern
- }
- func (req *Req) Cookie(name string) (string, error) {
- cookie, err := req.r.Cookie(name)
- if err != nil {
- return "", err
- }
- return cookie.Value, nil
- }
- func (req *Req) getParentPath() string {
- parentPath := ""
- arr := strings.Split(req.Path, "/")
- for i := 0; i < len(arr)-1; i++ {
- if arr[i] == "" {
- continue
- }
- parentPath += "/" + arr[i]
- }
- return parentPath
- }
|