66 lines
1.7 KiB
Go
66 lines
1.7 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"log/slog"
|
|
"net"
|
|
"net/http"
|
|
"nixcn-cms/api"
|
|
"nixcn-cms/middleware"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/spf13/viper"
|
|
swaggerFiles "github.com/swaggo/files"
|
|
ginSwagger "github.com/swaggo/gin-swagger"
|
|
"go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin"
|
|
|
|
_ "nixcn-cms/docs"
|
|
)
|
|
|
|
// @title NixCN CMS API
|
|
// @version 1.0
|
|
// @description API Docs based on Gin framework
|
|
// @termsOfService http://swagger.io/terms/
|
|
// @contact.name API Support
|
|
// @contact.url http://www.swagger.io/support
|
|
// @contact.email support@swagger.io
|
|
// @license.name Apache 2.0
|
|
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
|
|
// @host localhost:8000
|
|
// @BasePath /app/api/v1
|
|
// @schemes http https
|
|
func Start(ctx context.Context) {
|
|
if !viper.GetBool("server.debug_mode") {
|
|
gin.SetMode(gin.ReleaseMode)
|
|
gin.DisableConsoleColor()
|
|
}
|
|
|
|
r := gin.New()
|
|
r.Use(otelgin.Middleware(viper.GetString("server.service_name")))
|
|
r.Use(middleware.GinLogger())
|
|
|
|
if viper.GetBool("server.debug_mode") {
|
|
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
|
|
}
|
|
|
|
r.Use(gin.Recovery())
|
|
|
|
api.Handler(r.Group("/app/api/v1"))
|
|
|
|
// Start http server
|
|
server := &http.Server{
|
|
Addr: viper.GetString("server.address"),
|
|
Handler: r,
|
|
BaseContext: func(net.Listener) context.Context { return ctx },
|
|
ReadTimeout: 10 * time.Second,
|
|
WriteTimeout: 10 * time.Second,
|
|
MaxHeaderBytes: 1 << 20,
|
|
}
|
|
|
|
slog.InfoContext(ctx, "[Server] Starting server on "+viper.GetString("server.address"))
|
|
if err := server.ListenAndServe(); err != nil {
|
|
slog.ErrorContext(ctx, "[Server] Error starting server!", "err", err)
|
|
}
|
|
}
|