add backend tpl

This commit is contained in:
Rogee
2024-11-28 23:18:11 +08:00
parent 77e962b668
commit f7d95418a2
86 changed files with 3229 additions and 135 deletions

View File

@@ -0,0 +1,45 @@
package http
import (
"fmt"
)
const DefaultPrefix = "Http"
type Config struct {
StaticPath *string
StaticRoute *string
Host *string
Port uint
Tls *Tls
Cors *Cors
}
type Tls struct {
Cert string
Key string
}
type Cors struct {
Mode string
Whitelist []Whitelist
}
type Whitelist struct {
AllowOrigin string
AllowHeaders string
AllowMethods string
ExposeHeaders string
AllowCredentials bool
}
func (h *Config) Address() string {
if h.Host == nil {
return h.PortString()
}
return fmt.Sprintf("%s:%d", *h.Host, h.Port)
}
func (h *Config) PortString() string {
return fmt.Sprintf(":%d", h.Port)
}

View File

@@ -0,0 +1,8 @@
package http
type Route interface{}
type Service interface {
Serve() error
GetEngine() interface{}
}

View File

@@ -0,0 +1,78 @@
package fiber
import (
"time"
"backend/providers/http"
"git.ipao.vip/rogeecn/atom/container"
"git.ipao.vip/rogeecn/atom/utils/opt"
log "github.com/sirupsen/logrus"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/logger"
"github.com/gofiber/fiber/v2/middleware/recover"
)
func DefaultProvider() container.ProviderContainer {
return container.ProviderContainer{
Provider: Provide,
Options: []opt.Option{
opt.Prefix(http.DefaultPrefix),
},
}
}
type Service struct {
conf *http.Config
Engine *fiber.App
}
func (e *Service) Use(middleware ...interface{}) fiber.Router {
return e.Engine.Use(middleware...)
}
func (e *Service) GetEngine() interface{} {
return e.Engine
}
func (e *Service) Close() {
e.Engine.Shutdown()
}
func (e *Service) Serve() error {
if e.conf.Tls != nil {
return e.Engine.ListenTLS(e.conf.PortString(), e.conf.Tls.Cert, e.conf.Tls.Key)
}
return e.Engine.Listen(e.conf.PortString())
}
func Provide(opts ...opt.Option) error {
o := opt.New(opts...)
var config http.Config
if err := o.UnmarshalConfig(&config); err != nil {
return err
}
return container.Container.Provide(func(l *log.Logger) (http.Service, error) {
engine := fiber.New(fiber.Config{
EnablePrintRoutes: true,
StrictRouting: true,
})
engine.Use(recover.New())
if config.StaticRoute != nil && config.StaticPath != nil {
engine.Use(config.StaticRoute, config.StaticPath)
}
engine.Use(logger.New(logger.Config{
Format: `[${ip}:${port}] - [${time}] - ${method} - ${status} - ${path} ${latency} "${ua}"` + "\n",
TimeFormat: time.RFC1123,
TimeZone: "Asia/Shanghai",
}))
svc := &Service{Engine: engine, conf: &config}
container.AddCloseAble(svc.Close)
return svc, nil
}, o.DiOptions()...)
}