Files

53 lines
1.6 KiB
Go
Raw Permalink Normal View History

2026-07-31 16:59:55 +08:00
package httpapi
import (
"errors"
"log"
"time"
"github.com/gin-gonic/gin"
"git.apinb.com/ops/license/internal/dashboard"
"git.apinb.com/ops/license/internal/issuance"
"git.apinb.com/ops/license/internal/subject"
)
func NewRouter(subjectService *subject.Service, issuanceService *issuance.Service, dashboardService *dashboard.Service) (*gin.Engine, error) {
if subjectService == nil || issuanceService == nil || dashboardService == nil {
return nil, errors.New("HTTP API 依赖不能为空")
}
router := gin.New()
router.Use(gin.Recovery(), routeLogger())
subjects := subjectHandler{service: subjectService}
licences := issuanceHandler{service: issuanceService, subjectService: subjectService}
dashboardHandler := dashboardHandler{service: dashboardService}
api := router.Group("/api/v1")
api.GET("/dashboard", dashboardHandler.get)
api.GET("/subjects", subjects.list)
api.POST("/subjects", subjects.create)
api.GET("/subjects/:id", subjects.get)
api.PUT("/subjects/:id", subjects.update)
api.DELETE("/subjects/:id", subjects.delete)
api.POST("/subjects/:id/licences", licences.issue)
api.GET("/licences", licences.list)
api.GET("/licences/:id", licences.get)
api.GET("/licences/:id/download", licences.download)
api.POST("/licences/:id/renew", licences.renew)
return router, nil
}
func routeLogger() gin.HandlerFunc {
return func(c *gin.Context) {
startedAt := time.Now()
c.Next()
route := c.FullPath()
if route == "" {
route = c.Request.URL.Path
}
log.Printf("HTTP route=%s status=%d duration=%s", route, c.Writer.Status(), time.Since(startedAt).Round(time.Millisecond))
}
}