vegvisir/pkg/server/router.go

88 lines
2.0 KiB
Go
Raw Normal View History

// ___ ____ ___ ___
// \ \ / / | _ | __| \ \ / / || | __ || || _ |
// \ \/ / |___ | |__ \ \/ / || |___ || ||___|
// \ / | _ | _ | \ / || __ | || ||\\
// \/ |___ |___ | \/ || ____| || || \\
//
// Copyright (c) 2021 Piotr Biernat. https://pbiernat.dev. MIT License
// Repo: https://git.pbiernat.dev/golang/vegvisir
package server
import (
"fmt"
"regexp"
"strings"
"vegvisir/pkg/cache"
"vegvisir/pkg/config"
)
2021-08-03 00:13:14 +02:00
// Router struct
type Router struct {
config *config.Config
rcm cache.RouteCacheManager // Redis cache
rCache map[string]cache.RouteCache // Internal route cache - TMP?
}
2021-08-03 00:13:14 +02:00
// Route struct
type Route struct {
2021-08-03 00:13:14 +02:00
SourceURL string
TargetURL string
}
2021-08-03 00:13:14 +02:00
// NewRouter function
func NewRouter(conf *config.Config, cacheDS cache.Datastore, ttl int) *Router {
return &Router{
config: conf,
rcm: cache.NewRouteCacheManager(cacheDS, ttl),
rCache: make(map[string]cache.RouteCache),
}
}
2021-08-03 00:13:14 +02:00
// FindByRequestURL function
func (r *Router) FindByRequestURL(url []byte) (bool, Route) {
2021-08-03 00:13:14 +02:00
var sURL string = string(url)
2021-08-03 00:13:14 +02:00
for bID := range r.config.Backends {
bck := r.config.Backends[bID]
if !strings.Contains(sURL, bck.PrefixURL) {
continue
}
2021-08-03 00:13:14 +02:00
for rID := range bck.Routes {
routeCfg := &bck.Routes[rID]
// if ok, cRoute := s.rCacheManager.Load(sUri); ok {
// return true, cRoute
// }
2021-08-03 00:13:14 +02:00
if cRoute, ok := r.rCache[sURL]; ok {
route := Route{
2021-08-03 00:13:14 +02:00
SourceURL: cRoute.SourceURL,
TargetURL: cRoute.TargetURL,
}
return true, route
}
2021-08-03 00:13:14 +02:00
rgxp := regexp.MustCompile(fmt.Sprintf("%s%s", bck.PrefixURL, routeCfg.Pattern))
if rgxp.Match(url) {
2021-08-03 00:13:14 +02:00
targetURL := bck.BackendAddress + rgxp.ReplaceAllString(sURL, routeCfg.Target)
2021-08-03 00:13:14 +02:00
route := Route{ // FIXME: duplicated #1
SourceURL: sURL,
TargetURL: targetURL,
}
// s.rCacheManager.Save(sUri, cRoute)
2021-08-03 00:13:14 +02:00
r.rCache[sURL] = cache.RouteCache{ // FIXME: duplicated #1
SourceURL: route.SourceURL,
TargetURL: route.TargetURL,
}
return true, route
}
}
}
return false, Route{}
}