diff --git a/config/config.go b/config/config.go index 226151e..a82e0c0 100644 --- a/config/config.go +++ b/config/config.go @@ -1,8 +1,17 @@ package config +// ___ ____ ___ ___ +// \ \ / / | _ | __| \ \ / / || | __ || || _ | +// \ \/ / |___ | |__ \ \/ / || |___ || ||___| +// \ / | _ | _ | \ / || __ | || ||\\ +// \/ |___ |___ | \/ || ____| || || \\ + +// Copyright (c) 2021 Piotr Biernat. https://pbiernat.dev. MIT License +// Repo: https://git.pbiernat.dev/golang/vegvisir + type Config struct { Server Server - Services map[string]Service + Backends map[string]Backend } type Server struct { @@ -10,8 +19,19 @@ type Server struct { Port int } -type Service struct { - BaseURL string - ForwardTo string - Protocol string +type Backend struct { + PrefixUrl string + BackendAddress string + Protocol string + Routes []Route +} + +type Route struct { + Pattern string + Target string +} + +var DefaultRoute = Route{ + Pattern: "(.*)", + Target: "", } diff --git a/config/test/sample.json b/config/test/sample.json deleted file mode 100644 index b1c6df8..0000000 --- a/config/test/sample.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "server": { - "address": "127.0.0.1", - "port": 8080 - }, - "services": { - "test-app1": { - "baseUrl": "test/", - "forwardTo": "127.0.0.1:3030/", - "protocol": "http" - }, - "test-app2": { - "baseUrl": "test2/", - "forwardTo": "httpbin.org/", - "protocol": "http" - } - } -} \ No newline at end of file diff --git a/go.mod b/go.mod index f9239a4..e2fcb7c 100644 --- a/go.mod +++ b/go.mod @@ -2,4 +2,8 @@ module vegvisir go 1.13 -require github.com/opentracing/opentracing-go v1.2.0 // indirect +require ( + github.com/andybalholm/brotli v1.0.3 // indirect + github.com/klauspost/compress v1.13.1 // indirect + github.com/valyala/fasthttp v1.28.0 +) diff --git a/main.go b/main.go index 7fa23c6..3033f9d 100644 --- a/main.go +++ b/main.go @@ -10,10 +10,16 @@ package main // Repo: https://git.pbiernat.dev/golang/vegvisir import ( + "flag" "vegvisir/server" ) +var ( + cFile = flag.String("c", "vegvisir.json", "Path to config file") +) + func main() { - s := server.NewServer() - err := s.LoadConfig("config/test/sample.json") + flag.Parse() + + server.NewServer(*cFile).Run() } diff --git a/server/server.go b/server/server.go index 3f34598..33c9267 100644 --- a/server/server.go +++ b/server/server.go @@ -10,51 +10,154 @@ package server // Repo: https://git.pbiernat.dev/golang/vegvisir import ( + "context" "encoding/json" + "fmt" "io/ioutil" + "log" "os" + "os/signal" + "regexp" + "strings" + "time" "vegvisir/config" + + "github.com/valyala/fasthttp" +) + +const ( + Version = "0.1" + Name = "Vegvisir/" + Version ) type Server struct { Config config.Config + + cFilePath string + foundBackend *config.Backend + foundRoute *config.Route } -func NewServer() Server { - return Server{} +func NewServer(cPath string) *Server { + return &Server{ + cFilePath: cPath, + } } -func (s *Server) LoadConfig(file string) error { - if _, err := os.Stat(file); err != nil { +func (s *Server) Run() { + if err := s.loadConfig(); err != nil { + log.Fatalln("Unable to find config file: ", s.cFilePath, err) + } + + go func() { + serverAddress := s.Config.Server.Address + ":" + fmt.Sprint(s.Config.Server.Port) + if err := fasthttp.ListenAndServe(serverAddress, s.mainHandler); err != nil { + log.Fatalf("Server panic! Error message: %s", err) + } + }() + + log.Println("Server started") + + // Wait for an interrupt + interrupt := make(chan os.Signal, 1) + signal.Notify(interrupt, os.Interrupt, os.Kill) + <-interrupt + + log.Println("SIGKILL or SIGINT caught, shutting down...") + + // Attempt a graceful shutdown + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + s.Shutdown(ctx) + log.Println("Server shutdown successfully.") +} + +func (s *Server) Shutdown(ctx context.Context) { // TODO: wait for all connections to finish + log.Println("Shuting down finished") +} + +func (s *Server) loadConfig() error { + if _, err := os.Stat(s.cFilePath); err != nil { return err } - data, err := ioutil.ReadFile(file) + data, err := ioutil.ReadFile(s.cFilePath) if err != nil { return err } - json.Unmarshal(data, &s.Config) + err = json.Unmarshal(data, &s.Config) + if err != nil { + return err + } return nil } -// func Run(s *Server) { -// s.StartListener() +func (s *Server) mainHandler(ctx *fasthttp.RequestCtx) { + ctx.Response.Header.Add(fasthttp.HeaderServer, Name) -// log.Println("Server started successfully...") + // move all below logic to concrete handler or sth....? + reqURI, sReqURI, sReqMethod := ctx.RequestURI(), string(ctx.RequestURI()), string(ctx.Method()) + log.Println("Incomming request:", sReqMethod, sReqURI) -// Wait for an interrupt -// c := make(chan os.Signal, 1) -// signal.Notify(c, os.Interrupt, os.Kill) -// <-c + found, rgxp := s.findBackendAndRouteByRequestURI(reqURI) + if !found { + // FIXME: return 404/5xx error in repsonse, maybe define it in Backend config? + ctx.Response.SetStatusCode(fasthttp.StatusNotFound) + return + } -// log.Error("SIGKILL or SIGINT caught, shutting down...") + bckReqURI := s.buildBackendTargetURI(*rgxp, sReqURI) -// Attempt a graceful shutdown -// ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) -// defer cancel() + // prepare to send request to backend - separate + bckReq := fasthttp.AcquireRequest() + bckResp := fasthttp.AcquireResponse() + defer fasthttp.ReleaseRequest(bckReq) + defer fasthttp.ReleaseResponse(bckResp) -// s.shutdownServers(ctx) -// log.Error("all listeners shut down.") -// } + // copy headers from backend response and prepare request for backend - separate + bckReq.SetRequestURI(bckReqURI) + bckReq.Header.SetMethod(sReqMethod) + + fasthttp.Do(bckReq, bckResp) + + ctx.Response.Header.SetBytesV(fasthttp.HeaderContentType, bckResp.Header.ContentType()) + ctx.SetBody(bckResp.Body()) +} + +func (s *Server) findBackendAndRouteByRequestURI(uri []byte) (bool, *regexp.Regexp) { + for _, bck := range s.Config.Backends { + if !strings.Contains(string(uri), bck.PrefixUrl) { + continue + } + s.foundBackend = &bck // possibly errorneus... + + for _, r := range bck.Routes { + rgxp := regexp.MustCompile(fmt.Sprintf("%s%s", bck.PrefixUrl, r.Pattern)) + // fmt.Println("pattern: ", bck.PrefixUrl+r.Pattern, rgxp.Match(uri)) + if rgxp.Match(uri) { + s.foundBackend = &bck // 100% safe here + s.foundRoute = &r + + return true, rgxp + } + } + } + + return false, nil +} + +func (s *Server) buildBackendTargetURI(rgxp regexp.Regexp, uri string) string { + baseURI := s.foundBackend.BackendAddress + url := rgxp.ReplaceAllString(uri, s.foundRoute.Target) + + // if !strings.HasSuffix(baseURI, "/") { + // baseURI += "/" + // } + + log.Println("Send req to backend url: ", baseURI+url) + + return baseURI + url +} diff --git a/vegvisir.json b/vegvisir.json new file mode 100644 index 0000000..8394cc5 --- /dev/null +++ b/vegvisir.json @@ -0,0 +1,33 @@ +{ + "server": { + "address": "127.0.0.1", + "port": 8080 + }, + "backends": { + "news-app": { + "prefixUrl": "news/", + "backendAddress": "http://127.0.0.1:3030", + "routes": [{ + "pattern": "new/(.*)", + "target": "$1" + },{ + "pattern": "new1/(.*)/([0-9]*)", + "target": "new-url1/$1/$2" + },{ + "pattern": "(.+)", + "target": "url" + }] + }, + "article-app": { + "prefixUrl": "art/", + "backendAddress": "http://127.0.0.1:3030", + "routes": [{ + "pattern": "art1/(.*)", + "target": "art-url1/$1" + },{ + "pattern": "([a-zA-Z0-9]*)", + "target": "article-global/$1" + }] + } + } +} \ No newline at end of file