// ___ ____ ___ ___ // \ \ / / | _ | __| \ \ / / || | __ || || _ | // \ \/ / |___ | |__ \ \/ / || |___ || ||___| // \ / | _ | _ | \ / || __ | || ||\\ // \/ |___ |___ | \/ || ____| || || \\ // // 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" ) // Router struct type Router struct { config *config.Config rcm cache.RouteCacheManager // Redis cache rCache map[string]cache.RouteCache // Internal route cache - TMP? } // Route struct type Route struct { SourceURL string TargetURL string } // 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), } } // FindByRequestURL function func (r *Router) FindByRequestURL(url []byte) (bool, Route) { var sURL string = string(url) for bID := range r.config.Backends { bck := r.config.Backends[bID] if !strings.Contains(sURL, bck.PrefixURL) { continue } for rID := range bck.Routes { routeCfg := &bck.Routes[rID] // if ok, cRoute := s.rCacheManager.Load(sUri); ok { // return true, cRoute // } if cRoute, ok := r.rCache[sURL]; ok { route := Route{ SourceURL: cRoute.SourceURL, TargetURL: cRoute.TargetURL, } return true, route } rgxp := regexp.MustCompile(fmt.Sprintf("%s%s", bck.PrefixURL, routeCfg.Pattern)) if rgxp.Match(url) { targetURL := bck.BackendAddress + rgxp.ReplaceAllString(sURL, routeCfg.Target) route := Route{ // FIXME: duplicated #1 SourceURL: sURL, TargetURL: targetURL, } // s.rCacheManager.Save(sUri, cRoute) r.rCache[sURL] = cache.RouteCache{ // FIXME: duplicated #1 SourceURL: route.SourceURL, TargetURL: route.TargetURL, } return true, route } } } return false, Route{} }