2021-07-23 16:10:37 +02:00
|
|
|
// ___ ____ ___ ___
|
|
|
|
// \ \ / / | _ | __| \ \ / / || | __ || || _ |
|
|
|
|
// \ \/ / |___ | |__ \ \/ / || |___ || ||___|
|
|
|
|
// \ / | _ | _ | \ / || __ | || ||\\
|
|
|
|
// \/ |___ |___ | \/ || ____| || || \\
|
|
|
|
//
|
|
|
|
// Copyright (c) 2021 Piotr Biernat. https://pbiernat.dev. MIT License
|
|
|
|
// Repo: https://git.pbiernat.dev/golang/vegvisir
|
|
|
|
|
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"os"
|
|
|
|
"os/signal"
|
|
|
|
"time"
|
|
|
|
"vegvisir/pkg/cache"
|
|
|
|
"vegvisir/pkg/config"
|
|
|
|
|
|
|
|
"github.com/valyala/fasthttp"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2021-07-23 18:42:18 +02:00
|
|
|
Version = "0.1-dev"
|
2021-07-23 16:10:37 +02:00
|
|
|
Name = "Vegvisir/" + Version
|
|
|
|
)
|
|
|
|
|
|
|
|
type Server struct {
|
2021-07-24 17:46:22 +02:00
|
|
|
config *config.Config
|
|
|
|
router *Router
|
|
|
|
respCM cache.ResponseCacheManager // Redis response cache
|
2021-07-23 16:10:37 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewServer(cPath string) *Server {
|
2021-07-24 17:46:22 +02:00
|
|
|
config := config.New(cPath)
|
2021-07-23 16:10:37 +02:00
|
|
|
|
2021-07-24 17:46:22 +02:00
|
|
|
if err := config.Load(); err != nil {
|
|
|
|
log.Fatalln("Unable to find config file: ", cPath, err)
|
2021-07-23 16:10:37 +02:00
|
|
|
}
|
|
|
|
|
2021-07-24 17:46:22 +02:00
|
|
|
server := &Server{
|
|
|
|
config: config,
|
|
|
|
}
|
|
|
|
|
|
|
|
redisDS := cache.NewRedisDatastore("127.0.0.1", 6379) // FIXME use config or env...
|
|
|
|
if !redisDS.IsConnected() {
|
|
|
|
log.Println("Redis server not responding, switching to memory cache...")
|
|
|
|
|
|
|
|
memDS := cache.NewMemoryDatastore()
|
|
|
|
server.router = NewRouter(config, memDS, 30) //FIXME for memory datasource ttl is useles right now...
|
|
|
|
server.respCM = cache.NewResponseCacheManager(memDS, 30) //FIXME for memory datasource ttl is useles right now...
|
|
|
|
} else {
|
|
|
|
server.router = NewRouter(config, redisDS, 30) //FIXME use ttl(seconds) from config or env...
|
|
|
|
server.respCM = cache.NewResponseCacheManager(redisDS, 30) //FIXME use ttl(seconds) from config or env...
|
2021-07-23 16:10:37 +02:00
|
|
|
}
|
|
|
|
|
2021-07-24 17:46:22 +02:00
|
|
|
return server
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) Run() {
|
2021-07-23 16:10:37 +02:00
|
|
|
go func() {
|
2021-07-24 17:46:22 +02:00
|
|
|
serverAddress := s.config.Server.Address + ":" + fmt.Sprint(s.config.Server.Port)
|
2021-07-23 16:10:37 +02:00
|
|
|
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) mainHandler(ctx *fasthttp.RequestCtx) {
|
|
|
|
ctx.Response.Header.Add(fasthttp.HeaderServer, Name)
|
|
|
|
|
|
|
|
// move all below logic to concrete handler or sth....
|
2021-07-24 17:46:22 +02:00
|
|
|
reqUrl, sReqUrl, sReqMethod := ctx.RequestURI(), string(ctx.RequestURI()), string(ctx.Method())
|
|
|
|
log.Println("Incomming request:", sReqMethod, sReqUrl)
|
2021-07-23 16:10:37 +02:00
|
|
|
|
2021-07-24 17:46:22 +02:00
|
|
|
found, route := s.router.FindByRequestURL(reqUrl)
|
2021-07-23 16:10:37 +02:00
|
|
|
if !found {
|
|
|
|
// FIXME: return 404/5xx error in repsonse, maybe define it in Backend config?
|
|
|
|
ctx.SetStatusCode(fasthttp.StatusNotFound)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// handle response caching
|
2021-07-24 17:46:22 +02:00
|
|
|
if ok, data := s.respCM.Load(sReqUrl); ok {
|
2021-07-23 16:10:37 +02:00
|
|
|
log.Println("Read resp from cache: ", route.TargetUrl)
|
|
|
|
|
2021-07-24 17:46:22 +02:00
|
|
|
ctx.SetBody([]byte(data.Body)) // FIXME missing headers etc...
|
2021-07-23 16:10:37 +02:00
|
|
|
} else {
|
|
|
|
log.Println("Send req to backend url: ", route.TargetUrl)
|
|
|
|
|
|
|
|
// prepare to send request to backend - separate
|
|
|
|
bckReq := fasthttp.AcquireRequest()
|
|
|
|
bckResp := fasthttp.AcquireResponse()
|
|
|
|
defer fasthttp.ReleaseRequest(bckReq)
|
|
|
|
defer fasthttp.ReleaseResponse(bckResp)
|
|
|
|
|
|
|
|
// copy headers from backend response and prepare request for backend - separate
|
|
|
|
bckReq.SetRequestURI(route.TargetUrl)
|
|
|
|
bckReq.Header.SetMethod(sReqMethod)
|
|
|
|
|
|
|
|
err := fasthttp.Do(bckReq, bckResp)
|
|
|
|
if err != nil {
|
|
|
|
ctx.SetStatusCode(fasthttp.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
ctx.Response.Header.SetBytesV(fasthttp.HeaderContentType, bckResp.Header.ContentType())
|
|
|
|
ctx.SetStatusCode(bckResp.StatusCode())
|
|
|
|
ctx.SetBody(bckResp.Body())
|
|
|
|
|
|
|
|
// save response to cache
|
|
|
|
respCache := cache.ResponseCache{
|
2021-07-24 17:46:22 +02:00
|
|
|
URL: sReqUrl,
|
2021-07-23 16:10:37 +02:00
|
|
|
Body: string(bckResp.Body()),
|
|
|
|
// Headers: []
|
|
|
|
} // FIXME: prepare resp cache struct in respCM.Save method or other service...
|
2021-07-24 17:46:22 +02:00
|
|
|
s.respCM.Save(sReqUrl, respCache)
|
2021-07-23 16:10:37 +02:00
|
|
|
}
|
|
|
|
}
|