141 lines
5.3 KiB
Go
141 lines
5.3 KiB
Go
package server
|
|
|
|
import (
|
|
"log/slog"
|
|
"mime"
|
|
"net/http"
|
|
"os"
|
|
"path"
|
|
"strings"
|
|
"time"
|
|
|
|
"kra/internal/conf"
|
|
"kra/internal/server/handler"
|
|
"kra/internal/server/httpx"
|
|
servermiddleware "kra/internal/server/middleware"
|
|
serverrouter "kra/internal/server/router"
|
|
"kra/internal/service"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
kratoshttp "github.com/go-kratos/kratos/v3/transport/http"
|
|
)
|
|
|
|
func NewGinServer(c *conf.Server, runtime *conf.Runtime, system *service.SystemService, access *service.AccessService, authority *handler.Authority, menu *handler.Menu, api *handler.API, permission *handler.Permission, organization *handler.Organization, announcement *handler.Announcement, email *handler.Email, task *handler.Task, media *handler.Media, auditHandler *handler.Audit, export *handler.Export, version *handler.Version, dictionary *handler.Dictionary, parameter *handler.Parameter, apiToken *handler.APIToken, systemConfig *handler.SystemConfig, publicHandler *handler.Public, user *handler.User, navigation *handler.Navigation, session *handler.Session, settings *service.SettingsService, audit *service.AuditService, logger *slog.Logger) *kratoshttp.Server {
|
|
gin.SetMode(gin.ReleaseMode)
|
|
engine := gin.New()
|
|
engine.Use(servermiddleware.RequestMeta(), servermiddleware.Recovery(audit, logger), servermiddleware.AccessLog(runtime, logger), servermiddleware.ErrorAudit(audit), servermiddleware.SecurityRateLimit(system, settings), servermiddleware.OperationAudit(runtime, audit))
|
|
|
|
prefix := ""
|
|
config := runtime.Admin()
|
|
if config != nil {
|
|
prefix = strings.TrimSuffix(config.RouterPrefix, "/")
|
|
}
|
|
public := engine.Group(prefix)
|
|
public.GET("/health", func(c *gin.Context) { c.JSON(http.StatusOK, "ok") })
|
|
serverrouter.RegisterPublic(public, engine, publicHandler)
|
|
|
|
private := engine.Group(prefix)
|
|
private.Use(servermiddleware.Auth(runtime, settings), servermiddleware.MustChangePassword(), servermiddleware.AccessControl(runtime, access, audit))
|
|
serverrouter.RegisterUser(private, user)
|
|
serverrouter.RegisterNavigation(private, navigation)
|
|
serverrouter.RegisterSession(private, session)
|
|
serverrouter.RegisterAuthority(private, authority)
|
|
serverrouter.RegisterMenu(private, menu)
|
|
serverrouter.RegisterAPI(private, public, engine, api)
|
|
serverrouter.RegisterPermission(private, permission)
|
|
serverrouter.RegisterOrganization(private, organization)
|
|
serverrouter.RegisterDictionary(private, dictionary)
|
|
serverrouter.RegisterParameter(private, parameter)
|
|
serverrouter.RegisterAPIToken(private, apiToken)
|
|
serverrouter.RegisterSystemConfig(private, systemConfig)
|
|
serverrouter.RegisterVersion(private, version)
|
|
serverrouter.RegisterExport(private, public, export)
|
|
serverrouter.RegisterAudit(private, public, auditHandler)
|
|
serverrouter.RegisterTask(private, task)
|
|
serverrouter.RegisterMedia(private, media)
|
|
serverrouter.RegisterAnnouncement(private, public, announcement)
|
|
serverrouter.RegisterEmail(private, email)
|
|
|
|
engine.NoRoute(func(c *gin.Context) {
|
|
if serveLocalStorage(c, runtime) {
|
|
return
|
|
}
|
|
httpx.Fail(c, "请求的接口不存在")
|
|
})
|
|
|
|
network, address := "tcp", ":8000"
|
|
if c != nil && c.Http != nil {
|
|
if c.Http.Network != "" {
|
|
network = c.Http.Network
|
|
}
|
|
if c.Http.Addr != "" {
|
|
address = c.Http.Addr
|
|
}
|
|
}
|
|
timeout := 10 * time.Minute
|
|
if c != nil && c.Http != nil && c.Http.Timeout != nil && c.Http.Timeout.AsDuration() > 0 {
|
|
timeout = c.Http.Timeout.AsDuration()
|
|
}
|
|
server := kratoshttp.NewServer(kratoshttp.Network(network), kratoshttp.Address(address), kratoshttp.Timeout(timeout))
|
|
server.HandlePrefix("/", engine)
|
|
server.Server.ReadHeaderTimeout = 10 * time.Second
|
|
server.Server.ReadTimeout = timeout
|
|
server.Server.WriteTimeout = timeout
|
|
server.Server.IdleTimeout = 2 * time.Minute
|
|
server.Server.MaxHeaderBytes = 1 << 20
|
|
return server
|
|
}
|
|
|
|
// serveLocalStorage resolves the local path for every request so a config
|
|
// reload takes effect without rebuilding the Gin engine.
|
|
func serveLocalStorage(c *gin.Context, runtime *conf.Runtime) bool {
|
|
config := runtime.Admin()
|
|
if config == nil || config.Local == nil || config.Local.StorePath == "" {
|
|
return false
|
|
}
|
|
if config.Storage != nil && config.Storage.Type != "" && config.Storage.Type != "local" {
|
|
return false
|
|
}
|
|
prefix := "/" + strings.Trim(config.Local.PathPrefix, "/")
|
|
if prefix == "/" || (c.Request.URL.Path != prefix && !strings.HasPrefix(c.Request.URL.Path, prefix+"/")) {
|
|
return false
|
|
}
|
|
c.Header("X-Content-Type-Options", "nosniff")
|
|
filename := path.Base(c.Request.URL.Path)
|
|
if !canServeUploadInline(filename) {
|
|
c.Header("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": filename}))
|
|
}
|
|
http.StripPrefix(prefix, http.FileServer(filesOnly{FileSystem: http.Dir(config.Local.StorePath)})).ServeHTTP(c.Writer, c.Request)
|
|
return true
|
|
}
|
|
|
|
func canServeUploadInline(filename string) bool {
|
|
switch strings.ToLower(path.Ext(filename)) {
|
|
case ".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".ico", ".avif",
|
|
".mp3", ".wav", ".ogg", ".m4a", ".flac", ".aac",
|
|
".mp4", ".webm", ".mov", ".avi", ".mkv":
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
type filesOnly struct{ http.FileSystem }
|
|
|
|
func (f filesOnly) Open(name string) (http.File, error) {
|
|
file, err := f.FileSystem.Open(name)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
info, statErr := file.Stat()
|
|
if statErr != nil {
|
|
_ = file.Close()
|
|
return nil, statErr
|
|
}
|
|
if info.IsDir() {
|
|
_ = file.Close()
|
|
return nil, os.ErrPermission
|
|
}
|
|
return file, nil
|
|
}
|