The seed of reverse-proxy functionality

This commit is contained in:
Piotr Biernat 2021-07-10 23:57:45 +02:00
parent 9d897accb6
commit ba6b5b5564
6 changed files with 194 additions and 46 deletions

View File

@ -1,8 +1,17 @@
package config package config
// ___ ____ ___ ___
// \ \ / / | _ | __| \ \ / / || | __ || || _ |
// \ \/ / |___ | |__ \ \/ / || |___ || ||___|
// \ / | _ | _ | \ / || __ | || ||\\
// \/ |___ |___ | \/ || ____| || || \\
// Copyright (c) 2021 Piotr Biernat. https://pbiernat.dev. MIT License
// Repo: https://git.pbiernat.dev/golang/vegvisir
type Config struct { type Config struct {
Server Server Server Server
Services map[string]Service Backends map[string]Backend
} }
type Server struct { type Server struct {
@ -10,8 +19,19 @@ type Server struct {
Port int Port int
} }
type Service struct { type Backend struct {
BaseURL string PrefixUrl string
ForwardTo string BackendAddress string
Protocol string Protocol string
Routes []Route
}
type Route struct {
Pattern string
Target string
}
var DefaultRoute = Route{
Pattern: "(.*)",
Target: "",
} }

View File

@ -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"
}
}
}

6
go.mod
View File

@ -2,4 +2,8 @@ module vegvisir
go 1.13 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
)

10
main.go
View File

@ -10,10 +10,16 @@ package main
// Repo: https://git.pbiernat.dev/golang/vegvisir // Repo: https://git.pbiernat.dev/golang/vegvisir
import ( import (
"flag"
"vegvisir/server" "vegvisir/server"
) )
var (
cFile = flag.String("c", "vegvisir.json", "Path to config file")
)
func main() { func main() {
s := server.NewServer() flag.Parse()
err := s.LoadConfig("config/test/sample.json")
server.NewServer(*cFile).Run()
} }

View File

@ -10,51 +10,154 @@ package server
// Repo: https://git.pbiernat.dev/golang/vegvisir // Repo: https://git.pbiernat.dev/golang/vegvisir
import ( import (
"context"
"encoding/json" "encoding/json"
"fmt"
"io/ioutil" "io/ioutil"
"log"
"os" "os"
"os/signal"
"regexp"
"strings"
"time"
"vegvisir/config" "vegvisir/config"
"github.com/valyala/fasthttp"
)
const (
Version = "0.1"
Name = "Vegvisir/" + Version
) )
type Server struct { type Server struct {
Config config.Config Config config.Config
cFilePath string
foundBackend *config.Backend
foundRoute *config.Route
} }
func NewServer() Server { func NewServer(cPath string) *Server {
return Server{} return &Server{
cFilePath: cPath,
}
} }
func (s *Server) LoadConfig(file string) error { func (s *Server) Run() {
if _, err := os.Stat(file); err != nil { 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 return err
} }
data, err := ioutil.ReadFile(file) data, err := ioutil.ReadFile(s.cFilePath)
if err != nil { if err != nil {
return err return err
} }
json.Unmarshal(data, &s.Config) err = json.Unmarshal(data, &s.Config)
if err != nil {
return err
}
return nil return nil
} }
// func Run(s *Server) { func (s *Server) mainHandler(ctx *fasthttp.RequestCtx) {
// s.StartListener() 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 found, rgxp := s.findBackendAndRouteByRequestURI(reqURI)
// c := make(chan os.Signal, 1) if !found {
// signal.Notify(c, os.Interrupt, os.Kill) // FIXME: return 404/5xx error in repsonse, maybe define it in Backend config?
// <-c ctx.Response.SetStatusCode(fasthttp.StatusNotFound)
return
}
// log.Error("SIGKILL or SIGINT caught, shutting down...") bckReqURI := s.buildBackendTargetURI(*rgxp, sReqURI)
// Attempt a graceful shutdown // prepare to send request to backend - separate
// ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) bckReq := fasthttp.AcquireRequest()
// defer cancel() bckResp := fasthttp.AcquireResponse()
defer fasthttp.ReleaseRequest(bckReq)
defer fasthttp.ReleaseResponse(bckResp)
// s.shutdownServers(ctx) // copy headers from backend response and prepare request for backend - separate
// log.Error("all listeners shut down.") 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
}

33
vegvisir.json Normal file
View File

@ -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"
}]
}
}
}