RoadSign/pkg/sign/router.go

59 lines
1.6 KiB
Go
Raw Normal View History

2023-11-17 17:42:04 +00:00
package sign
import (
"code.smartsheep.studio/goatworks/roadsign/pkg/sign/transformers"
2023-11-17 17:42:04 +00:00
"errors"
"math/rand"
"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:
return makeHypertextResponse(ctx, upstream)
2023-11-17 17:42:04 +00:00
case UpstreamTypeFile:
return makeFileResponse(ctx, upstream)
2023-11-17 17:42:04 +00:00
default:
return fiber.ErrBadGateway
}
}
type RequestTransformerConfig = transformers.RequestTransformerConfig
2023-11-17 17:42:04 +00:00
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
}