// ___ ____ ___ ___ // \ \ / / | _ | __| \ \ / / || | __ || || _ | // \ \/ / |___ | |__ \ \/ / || |___ || ||___| // \ / | _ | _ | \ / || __ | || ||\\ // \/ |___ |___ | \/ || ____| || || \\ // // 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{} }