RoadSign/pkg/sign/upstream.go

56 lines
1.1 KiB
Go
Raw Normal View History

2023-11-17 17:42:04 +00:00
package sign
2023-11-17 16:23:40 +00:00
import (
"fmt"
2023-11-17 17:42:04 +00:00
"net/url"
2023-11-17 16:23:40 +00:00
"strings"
2023-12-10 03:30:31 +00:00
"github.com/gofiber/fiber/v2"
"github.com/samber/lo"
2023-11-17 16:23:40 +00:00
)
const (
UpstreamTypeFile = "file"
UpstreamTypeHypertext = "hypertext"
UpstreamTypeUnknown = "unknown"
)
type UpstreamConfig struct {
2023-12-10 03:30:31 +00:00
ID string `json:"id" yaml:"id"`
URI string `json:"uri" yaml:"uri"`
2023-11-17 16:23:40 +00:00
}
func (v *UpstreamConfig) GetType() string {
protocol := strings.SplitN(v.URI, "://", 2)[0]
switch protocol {
2023-12-10 03:30:31 +00:00
case "file", "files":
2023-11-17 16:23:40 +00:00
return UpstreamTypeFile
2023-12-10 03:30:31 +00:00
case "http", "https":
2023-11-17 16:23:40 +00:00
return UpstreamTypeHypertext
}
return UpstreamTypeUnknown
}
2023-11-17 17:42:04 +00:00
func (v *UpstreamConfig) GetRawURI() (string, url.Values) {
uri := strings.SplitN(v.URI, "://", 2)[1]
data := strings.SplitN(uri, "?", 2)
qs, _ := url.ParseQuery(uri)
return data[0], qs
}
2023-11-17 16:23:40 +00:00
func (v *UpstreamConfig) MakeURI(ctx *fiber.Ctx) string {
var queries []string
for k, v := range ctx.Queries() {
queries = append(queries, fmt.Sprintf("%s=%s", k, v))
}
path := string(ctx.Request().URI().Path())
hash := string(ctx.Request().URI().Hash())
return v.URI + path +
lo.Ternary(len(queries) > 0, "?"+strings.Join(queries, "&"), "") +
lo.Ternary(len(hash) > 0, "#"+hash, "")
}