[fix] Refactor URL handling in NewRequestContext and parseArgs functions

This commit is contained in:
Max 2023-12-16 14:01:46 +08:00
parent 37e4fde507
commit bd798b03cc
3 changed files with 33 additions and 3 deletions

View file

@ -32,6 +32,18 @@ func NewRequestContext(c *gin.Context) (*Request, int, error) {
return nil, 500, err
}
schema := c.Request.URL.Scheme
if schema == "" {
schema = "http"
}
domain := c.Request.URL.Hostname()
if domain == "" {
domain = strings.Split(c.Request.Host, ":")[0]
}
path := strings.TrimSuffix(c.Request.URL.Path, ".sui")
return &Request{
File: file,
Request: &core.Request{
@ -43,10 +55,11 @@ func NewRequestContext(c *gin.Context) (*Request, int, error) {
Headers: url.Values(c.Request.Header),
Params: params,
URL: core.ReqeustURL{
URL: fmt.Sprintf("%s://%s%s", schema, c.Request.Host, path),
Host: c.Request.Host,
Path: c.Request.URL.Path,
Domain: c.Request.URL.Hostname(),
Scheme: c.Request.URL.Scheme,
Path: path,
Domain: domain,
Scheme: schema,
},
},
}, 200, nil

View file

@ -221,6 +221,7 @@ func (r *Request) parseArgs(args []interface{}) ([]interface{}, error) {
"header": r.Headers,
"theme": r.Theme,
"locale": r.Locale,
"url": r.URL.Map(),
}).Dot()
for i, arg := range args {
@ -232,6 +233,7 @@ func (r *Request) parseArgs(args []interface{}) ([]interface{}, error) {
args[i] = key
if data.Has(key) {
v := data.Get(key)
args[i] = v
if strings.HasPrefix(key, "query.") || strings.HasPrefix(key, "header.") {
switch arg := v.(type) {
case []interface{}:
@ -246,6 +248,7 @@ func (r *Request) parseArgs(args []interface{}) ([]interface{}, error) {
}
}
}
break
case []interface{}:
res, err := r.parseArgs(v)
@ -253,6 +256,7 @@ func (r *Request) parseArgs(args []interface{}) ([]interface{}, error) {
return nil, err
}
args[i] = res
break
case map[string]interface{}:
res, err := r.parseArgs([]interface{}{v})
@ -260,12 +264,24 @@ func (r *Request) parseArgs(args []interface{}) ([]interface{}, error) {
return nil, err
}
args[i] = res[0]
break
}
}
return args, nil
}
// Map URL to map
func (url ReqeustURL) Map() Data {
return map[string]interface{}{
"url": url.URL,
"scheme": url.Scheme,
"domain": url.Domain,
"host": url.Host,
"path": url.Path,
}
}
// SetCache set the cache
func SetCache(file string, html string, data string, global string) *Cache {
Caches[file] = &Cache{

View file

@ -230,6 +230,7 @@ type ReqeustURL struct {
Domain string `json:"domain,omitempty"`
Path string `json:"path,omitempty"`
Scheme string `json:"scheme,omitempty"`
URL string `json:"url,omitempty"`
}
// PageConfig is the struct for the page config