123 lines
2.3 KiB
Go
123 lines
2.3 KiB
Go
package http
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"net/url"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"forge.cadoles.com/Cadoles/go-proxy/wildcard"
|
|
"github.com/expr-lang/expr"
|
|
"github.com/pkg/errors"
|
|
)
|
|
|
|
func setRequestHostFunc(r *http.Request) expr.Option {
|
|
return expr.Function(
|
|
"set_host",
|
|
func(params ...any) (any, error) {
|
|
host := params[0].(string)
|
|
r.Host = host
|
|
|
|
return true, nil
|
|
},
|
|
new(func(string) bool),
|
|
)
|
|
}
|
|
|
|
func setRequestURL(r *http.Request) expr.Option {
|
|
return expr.Function(
|
|
"set_url",
|
|
func(params ...any) (any, error) {
|
|
rawURL := params[0].(string)
|
|
|
|
url, err := url.Parse(rawURL)
|
|
if err != nil {
|
|
return false, errors.WithStack(err)
|
|
}
|
|
|
|
r.URL = url
|
|
|
|
return true, nil
|
|
},
|
|
new(func(string) bool),
|
|
)
|
|
}
|
|
|
|
func addRequestHeaderFunc(r *http.Request) expr.Option {
|
|
return expr.Function(
|
|
"add_header",
|
|
func(params ...any) (any, error) {
|
|
name := params[0].(string)
|
|
rawValue := params[1]
|
|
|
|
var value string
|
|
switch v := rawValue.(type) {
|
|
case []string:
|
|
value = strings.Join(v, ",")
|
|
case time.Time:
|
|
value = strconv.FormatInt(v.UTC().Unix(), 10)
|
|
case time.Duration:
|
|
value = strconv.FormatInt(int64(v.Seconds()), 10)
|
|
default:
|
|
value = fmt.Sprintf("%v", rawValue)
|
|
}
|
|
|
|
r.Header.Add(name, value)
|
|
|
|
return true, nil
|
|
},
|
|
new(func(string, string) bool),
|
|
)
|
|
}
|
|
|
|
func setRequestHeaderFunc(r *http.Request) expr.Option {
|
|
return expr.Function(
|
|
"set_header",
|
|
func(params ...any) (any, error) {
|
|
name := params[0].(string)
|
|
rawValue := params[1]
|
|
|
|
var value string
|
|
switch v := rawValue.(type) {
|
|
case []string:
|
|
value = strings.Join(v, ",")
|
|
case time.Time:
|
|
value = strconv.FormatInt(v.UTC().Unix(), 10)
|
|
case time.Duration:
|
|
value = strconv.FormatInt(int64(v.Seconds()), 10)
|
|
default:
|
|
value = fmt.Sprintf("%v", rawValue)
|
|
}
|
|
|
|
r.Header.Set(name, value)
|
|
|
|
return true, nil
|
|
},
|
|
new(func(string, string) bool),
|
|
)
|
|
}
|
|
|
|
func delRequestHeadersFunc(r *http.Request) expr.Option {
|
|
return expr.Function(
|
|
"del_headers",
|
|
func(params ...any) (any, error) {
|
|
pattern := params[0].(string)
|
|
deleted := false
|
|
|
|
for key := range r.Header {
|
|
if !wildcard.Match(key, pattern) {
|
|
continue
|
|
}
|
|
|
|
r.Header.Del(key)
|
|
deleted = true
|
|
}
|
|
|
|
return deleted, nil
|
|
},
|
|
new(func(string) bool),
|
|
)
|
|
}
|