You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

124 lines
3.0 KiB
Go

package router
import (
"fmt"
"strings"
"time"
u "ziqian/utils"
"github.com/gin-gonic/gin"
)
func SetupRouter() *gin.Engine {
r := gin.Default()
r.LoadHTMLFiles("templates/index.html")
// 只在开发环境中配置静态文件服务
if gin.Mode() == gin.DebugMode {
// 配置静态文件服务
r.Static("/static", "./static")
fmt.Println("Development mode: Static file services enabled")
} else {
fmt.Println("Production mode: Static file services disabled")
}
// 添加CORS中间件
r.Use(func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
})
r.GET("/", func(c *gin.Context) {
u.Zi.Html(c, "index.html", gin.H{
"Title": "Ziqian API",
"Subtitle": "基于 Gin 框架的 API 服务",
"CurrentTime": time.Now().Format("2006-01-02 15:04:05"),
"Version": "1.0.0",
"Year": time.Now().Year(),
})
})
apiGroup := r.Group("/api")
{
apiGroup.Any("/ho", func(c *gin.Context) {
u.Zi.Echo(c, gin.H{
"status": "ok",
})
})
apiGroup.Any("/map", func(c *gin.Context) {
cParam := c.Query("c")
typeList := strings.Split(cParam, ",")
if cParam == "" {
typeList = nil
}
processed := make(map[string]bool)
apiRoutes := make(map[string]string)
protocol := "http"
xForwardedProto := c.GetHeader("X-Forwarded-Proto")
xScheme := c.GetHeader("X-Scheme")
if c.Request.TLS != nil || xForwardedProto == "https" || xScheme == "https" {
protocol = "https"
}
host := c.Request.Host
for _, route := range r.Routes() {
path := route.Path
if !strings.HasPrefix(path, "/api/") || path == "/api/map" || processed[path] {
continue
}
processed[path] = true
keyName := ""
for i, part := range strings.Split(strings.TrimPrefix(path, "/api/"), "/") {
if part == "" {
continue
}
upperPart := strings.ToUpper(string(part[0])) + part[1:]
keyName += func() string {
if i > 0 {
return "_" + upperPart
}
return upperPart
}()
}
if typeList != nil {
typePrefix := strings.ToLower(strings.Split(keyName, "_")[0])
matched := false
for _, t := range typeList {
if strings.ToLower(t) == typePrefix {
matched = true
break
}
}
if !matched {
continue
}
}
apiRoutes[keyName] = fmt.Sprintf("%s://%s%s", protocol, host, path)
}
apiRoutes["Map"] = fmt.Sprintf("%s://%s%s", protocol, host, "/api/map")
apiRoutes["Ho"] = fmt.Sprintf("%s://%s%s", protocol, host, "/api/ho")
u.Zi.Echo(c, apiRoutes)
})
}
return r
}