vegvisir/pkg/server/router.go
Piotr Biernat 6392d7088e
All checks were successful
continuous-integration/drone/push Build is passing
Router FindByRequestURL() fix
2022-04-05 01:23:44 +02:00

78 lines
2.1 KiB
Go

// ___ ____ ___ ___
// \ \ / / | _ | __| \ \ / / || | __ || || _ |
// \ \/ / |___ | |__ \ \/ / || |___ || ||___|
// \ / | _ | _ | \ / || __ | || ||\\
// \/ |___ |___ | \/ || ____| || || \\
//
// Copyright (c) 2021 Piotr Biernat. https://pbiernat.dev. MIT License
// Repo: https://git.pbiernat.dev/golang/vegvisir
package server
import (
"fmt"
"git.pbiernat.dev/golang/vegvisir/pkg/cache"
"git.pbiernat.dev/golang/vegvisir/pkg/config"
"log"
"regexp"
"strings"
)
// Router struct
type Router struct {
config *config.Config
cache *cache.MemoryDatastore
}
// NewRouter function
func NewRouter(config *config.Config, ds *cache.MemoryDatastore, ttl int) *Router {
return &Router{
config: config,
cache: ds,
//cache: cache.NewRedisDatastore(config.Cache.Host, config.Cache.Password, config.Cache.Database, config.Cache.Port),
}
}
// FindByRequestURL function
func (r *Router) FindByRequestURL(url []byte) (bool, *cache.RouteCache) {
var sURL = string(url)
//if cRoute, ok := r.cache[sURL]; ok {
if cRoute, err := r.cache.GetKey("route_" + sURL); err == nil {
return true, cRoute.(*cache.RouteCache)
//response := &cache.RouteCache{} // FIXME #67: Simplify
//ffjson.Unmarshal([]byte(cRoute.(string)), response)
//return true, response // FIXME: redis cache tmp
}
for bID := range r.config.Backends {
bck := r.config.Backends[bID]
if !strings.Contains(sURL, bck.PrefixURL) {
continue
}
for rID := range bck.Routes {
rCfg := &bck.Routes[rID]
regxp := regexp.MustCompile(fmt.Sprintf("%s%s", bck.PrefixURL, rCfg.Pattern))
if regxp.Match(url) {
tURL := bck.BackendAddress + regxp.ReplaceAllString(sURL, rCfg.Target)
route := cache.NewRouteCache(sURL, tURL)
//routeJSON, _ := ffjson.Marshal(&route) // FIXME: TMP
if err := r.cache.SetKey("route_"+sURL, route, r.config.Cache.RouteTTL); err != nil {
// FIXME: ^^ use cache.Manager* after refactor
log.Println("Error saving route cache:", sURL)
}
log.Println("Saved route:", sURL, route.TargetURL)
return true, route
}
}
}
return false, &cache.RouteCache{}
}