2023-11-17 17:42:04 +00:00
|
|
|
package sign
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"math/rand"
|
2023-11-25 15:00:34 +00:00
|
|
|
|
|
|
|
"github.com/gofiber/fiber/v2"
|
2023-12-10 03:30:31 +00:00
|
|
|
"github.com/rs/zerolog/log"
|
2023-11-17 17:42:04 +00:00
|
|
|
)
|
|
|
|
|
2023-12-12 13:07:05 +00:00
|
|
|
type RoadApp struct {
|
2023-12-10 03:30:31 +00:00
|
|
|
Sites []*SiteConfig `json:"sites"`
|
2023-11-17 17:42:04 +00:00
|
|
|
}
|
|
|
|
|
2023-12-12 13:07:05 +00:00
|
|
|
func (v *RoadApp) Forward(ctx *fiber.Ctx, site *SiteConfig) error {
|
2023-11-17 17:42:04 +00:00
|
|
|
if len(site.Upstreams) == 0 {
|
|
|
|
return errors.New("invalid configuration")
|
|
|
|
}
|
|
|
|
|
2023-12-10 03:30:31 +00:00
|
|
|
// Boot processes
|
|
|
|
for _, process := range site.Processes {
|
|
|
|
if err := process.BootProcess(); err != nil {
|
|
|
|
log.Warn().Err(err).Msgf("An error occurred when booting process (%s) for %s", process.ID, site.ID)
|
|
|
|
return fiber.ErrBadGateway
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Do forward
|
2023-11-17 17:42:04 +00:00
|
|
|
idx := rand.Intn(len(site.Upstreams))
|
2023-12-10 03:30:31 +00:00
|
|
|
upstream := site.Upstreams[idx]
|
2023-11-17 17:42:04 +00:00
|
|
|
|
|
|
|
switch upstream.GetType() {
|
|
|
|
case UpstreamTypeHypertext:
|
2023-11-25 15:00:34 +00:00
|
|
|
return makeHypertextResponse(ctx, upstream)
|
2023-11-17 17:42:04 +00:00
|
|
|
case UpstreamTypeFile:
|
2023-11-25 15:00:34 +00:00
|
|
|
return makeFileResponse(ctx, upstream)
|
2023-11-17 17:42:04 +00:00
|
|
|
default:
|
|
|
|
return fiber.ErrBadGateway
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type SiteConfig struct {
|
2023-12-10 03:30:31 +00:00
|
|
|
ID string `json:"id"`
|
|
|
|
Rules []*RouterRuleConfig `json:"rules" yaml:"rules"`
|
|
|
|
Transformers []*RequestTransformerConfig `json:"transformers" yaml:"transformers"`
|
|
|
|
Upstreams []*UpstreamConfig `json:"upstreams" yaml:"upstreams"`
|
|
|
|
Processes []*ProcessConfig `json:"processes" yaml:"processes"`
|
2023-11-17 17:42:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type RouterRuleConfig struct {
|
2023-12-10 03:30:31 +00:00
|
|
|
Host []string `json:"host" yaml:"host"`
|
|
|
|
Path []string `json:"path" yaml:"path"`
|
|
|
|
Queries map[string]string `json:"queries" yaml:"queries"`
|
|
|
|
Headers map[string][]string `json:"headers" yaml:"headers"`
|
2023-11-17 17:42:04 +00:00
|
|
|
}
|