server added

This commit is contained in:
2023-07-31 18:30:43 +02:00
parent dbbd2884ea
commit 2d7db4467a
66 changed files with 13251 additions and 105 deletions
+31
View File
@@ -0,0 +1,31 @@
package service
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
func CorsMiddleware() gin.HandlerFunc {
headers := []string{"Content-Type", "Content-Length", "Accept-Encoding", "X-CSRF-Token", "Authorization"}
headerList := strings.Join(headers, ",")
methods := []string{"POST", "GET", "OPTIONS", "PUT", "DELETE", "UPDATE"}
methodList := strings.Join(methods, ",")
return func(gctx *gin.Context) {
gctx.Writer.Header().Set("Access-Control-Allow-Origin", "*")
gctx.Writer.Header().Set("Access-Control-Max-Age", "86400")
gctx.Writer.Header().Set("Access-Control-Allow-Methods", methodList)
gctx.Writer.Header().Set("Access-Control-Allow-Headers", headerList)
gctx.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
if gctx.Request.Method == "OPTIONS" {
gctx.AbortWithStatus(http.StatusOK)
} else {
gctx.Next()
}
}
}
+59
View File
@@ -0,0 +1,59 @@
package service
import (
"bytes"
"fmt"
"time"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
)
func LogMiddleware() gin.HandlerFunc {
return func(ctx *gin.Context) {
start := time.Now()
ctx.Next()
var reqSize int64
var method string
var reqURI string
if ctx.Request != nil {
reqSize = ctx.Request.ContentLength
method = ctx.Request.Method
reqURI = ctx.Request.RequestURI
}
duration := time.Since(start).Microseconds()
remAddr := ctx.RemoteIP()
var resCode int
var resSize int
if ctx.Writer != nil {
resCode = ctx.Writer.Status()
resSize = ctx.Writer.Size()
}
logString := fmt.Sprintf("%s %s %s in=%d out=%d res=%d %dms",
remAddr, method, reqURI, reqSize, resSize, resCode, duration)
logger := logrus.WithField("object", "accesslog")
logger.Infoln(logString)
}
}
type LogWriter struct {
gin.ResponseWriter
body *bytes.Buffer
}
func (lw LogWriter) Write(data []byte) (int, error) {
lw.body.Write(data)
return lw.ResponseWriter.Write(data)
}
func (lw LogWriter) WriteString(data string) (int, error) {
lw.body.WriteString(data)
return lw.ResponseWriter.WriteString(data)
}
+139
View File
@@ -0,0 +1,139 @@
package service
import (
"context"
"crypto/tls"
"fmt"
"net/http"
"path/filepath"
"time"
"strings"
"engine/internal/handler"
"engine/internal/logger"
"engine/pkg/auxtool/aux509"
"engine/pkg/auxtool/auxhttp"
"github.com/gin-gonic/gin"
)
const (
httpTimeout = 360
)
type ServiceConfig struct {
Handler *handler.Handler
PortNum int
WebDir string
}
type Service struct {
hand *handler.Handler
hsrv *http.Server
log *logger.Logger
engine *gin.Engine
portnum int
webdir string
}
func NewService(conf *ServiceConfig) (*Service, error) {
var err error
svc := &Service{
hand: conf.Handler,
portnum: conf.PortNum,
webdir: conf.WebDir,
}
svc.log = logger.NewLogger("service")
return svc, err
}
func (svc *Service) Build() error {
var err error
svc.log.Debugf("Build service")
gin.SetMode(gin.ReleaseMode)
gin.DisableConsoleColor()
svc.engine = gin.New()
svc.engine.Use(gin.Recovery())
svc.engine.Use(CorsMiddleware())
svc.engine.Use(LogMiddleware())
rootPath := filepath.Join(svc.webdir)
cssPath := filepath.Join(rootPath, "css")
fontsPath := filepath.Join(rootPath, "fonts")
jsPath := filepath.Join(rootPath, "js")
indexPath := filepath.Join(rootPath, "index.html")
svc.engine.Use(Serve("/", LocalFile(rootPath, false)))
svc.engine.Static("/css", cssPath)
svc.engine.Static("/fonts", fontsPath)
svc.engine.Static("/js", jsPath)
apiGroup := svc.engine.Group("api")
v1Group := apiGroup.Group("v1")
{
sessionGroup := v1Group.Group("session")
sessionGroup.POST("create", svc.hand.CreateSession)
healthGroup := v1Group.Group("health")
healthGroup.POST("get", svc.hand.GetHealth)
}
svc.engine.StaticFile("/", indexPath)
noRouteFunc := func(gctx *gin.Context) {
contentType := gctx.GetHeader("Content-Type")
contentType = strings.ToLower(contentType)
if strings.Contains(contentType, "application/json") {
err := fmt.Errorf("No route")
auxhttp.SendError(gctx, err)
} else {
gctx.Redirect(301, "/")
}
}
svc.engine.NoRoute(noRouteFunc)
cert, err := aux509.GetTLSCert("WEB", "ENGINE")
if err != nil {
return err
}
tlsConfig := tls.Config{
Certificates: []tls.Certificate{cert},
ClientAuth: tls.NoClientCert,
InsecureSkipVerify: true,
}
listenAddr := fmt.Sprintf(":%d", svc.portnum)
svc.hsrv = &http.Server{
Addr: listenAddr,
Handler: svc.engine,
TLSConfig: &tlsConfig,
}
return err
}
func (svc *Service) Run() error {
var err error
for _, route := range svc.engine.Routes() {
svc.log.Debugf("The route is registered: %s %s", route.Method, route.Path)
}
svc.log.Infof("Service listening at %d port", svc.portnum)
err = svc.hsrv.ListenAndServeTLS("", "")
if err != nil {
return err
}
return err
}
func (svc *Service) Stop() {
svc.log.Infof("Stopping service")
if svc.hsrv != nil {
downWaiting := 5 * time.Second
ctx, _ := context.WithTimeout(context.Background(), downWaiting)
svc.hsrv.Shutdown(ctx)
}
}
+58
View File
@@ -0,0 +1,58 @@
package service
import (
"net/http"
"os"
"path"
"strings"
"github.com/gin-gonic/gin"
)
func Serve(urlPrefix string, fs ServeFileSystem) gin.HandlerFunc {
fileserver := http.FileServer(fs)
if urlPrefix != "" {
fileserver = http.StripPrefix(urlPrefix, fileserver)
}
return func(c *gin.Context) {
if fs.Exists(urlPrefix, c.Request.URL.Path) {
fileserver.ServeHTTP(c.Writer, c.Request)
c.Abort()
}
}
}
type ServeFileSystem interface {
http.FileSystem
Exists(prefix string, path string) bool
}
type LocalFileSystem struct {
http.FileSystem
root string
indexes bool
}
func (l *LocalFileSystem) Exists(prefix string, filepath string) bool {
p := strings.TrimPrefix(filepath, prefix)
if len(p) < len(filepath) {
name := path.Join(l.root, p)
stats, err := os.Stat(name)
if err != nil {
return false
}
if !l.indexes && stats.IsDir() {
return false
}
return true
}
return false
}
func LocalFile(root string, indexes bool) *LocalFileSystem {
return &LocalFileSystem{
FileSystem: gin.Dir(root, indexes),
root: root,
indexes: indexes,
}
}