- Replace global variable pattern with proper dependency injection - Add uber-go/fx for automatic dependency resolution - Refactor all services and handlers to use constructor injection - Eliminate fragile initialization order dependencies - Improve testability and modularity - Add structured logging with zap Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
71 lines
2.0 KiB
Go
71 lines
2.0 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
|
|
"CatsOfMastodonBotGo/internal/web/handlers"
|
|
|
|
"github.com/gin-contrib/cors"
|
|
"github.com/gin-contrib/static"
|
|
"github.com/gin-gonic/gin"
|
|
"go.uber.org/fx"
|
|
)
|
|
|
|
// fx.In allows fx to inject multiple dependencies
|
|
type RouterParams struct {
|
|
fx.In
|
|
|
|
Lifecycle fx.Lifecycle
|
|
AdminDashboard *handlers.AdminDashboardHandler
|
|
ApiEndpoint *handlers.ApiEndpointHandler
|
|
EmbedCard *handlers.EmbedCardHandler
|
|
OauthLogin *handlers.OauthLoginHandler
|
|
}
|
|
|
|
func SetupRouter(params RouterParams) {
|
|
r := gin.Default()
|
|
|
|
r.Use(cors.New(cors.Config{
|
|
AllowAllOrigins: true,
|
|
AllowMethods: []string{"POST", "GET", "OPTIONS"},
|
|
AllowHeaders: []string{"Origin", "Content-Type", "Authorization"},
|
|
AllowCredentials: true,
|
|
}))
|
|
|
|
r.LoadHTMLGlob("internal/web/templates/home/*")
|
|
|
|
// Main page
|
|
r.GET("/", func(c *gin.Context) {
|
|
c.HTML(http.StatusOK, "home/index.html", nil)
|
|
})
|
|
// Embed card
|
|
r.GET("/embed", params.EmbedCard.GetEmbedCard)
|
|
|
|
admin := r.Group("/admin")
|
|
|
|
r.Use(static.Serve("/admin", static.LocalFile("internal/web/templates/admin", true)))
|
|
r.Use(static.Serve("/admin/oauth/gitea/callback", static.LocalFile("internal/web/templates/admin", true)))
|
|
|
|
adminApi := admin.Group("/api")
|
|
adminApi.POST("/login", params.AdminDashboard.Login)
|
|
adminApi.GET("/login/oauth/gitea", params.OauthLogin.GoToGiteaLogin)
|
|
adminApi.POST("/login/oauth/gitea/final", params.OauthLogin.LoginWithGitea)
|
|
adminApi.GET("/getmedia", params.AdminDashboard.JWTMiddleware(), params.AdminDashboard.GetMedia)
|
|
adminApi.POST("/approve", params.AdminDashboard.JWTMiddleware(), params.AdminDashboard.ApproveMedia)
|
|
adminApi.POST("/reject", params.AdminDashboard.JWTMiddleware(), params.AdminDashboard.RejectMedia)
|
|
|
|
api := r.Group("/api")
|
|
api.GET("/post/random", params.ApiEndpoint.GetRandomPost)
|
|
|
|
params.Lifecycle.Append(fx.Hook{
|
|
OnStart: func(ctx context.Context) error {
|
|
go func() {
|
|
if err := r.Run(":8080"); err != nil {
|
|
// Handle error appropriately
|
|
}
|
|
}()
|
|
return nil
|
|
},
|
|
})
|
|
} |