This commit is contained in:
2024-09-24 13:31:28 +08:00
parent 2bdc5e666b
commit e952657166
17 changed files with 521 additions and 85 deletions

30
router/middleware/cors.go Normal file
View File

@ -0,0 +1,30 @@
package middleware
import (
"time"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
// Cors 跨域中间件
func Cors() gin.HandlerFunc {
return cors.New(cors.Config{
// 允许跨域请求网站
AllowOrigins: []string{"*"},
// 允许使用的请求方式
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"},
// 允许使用的请求头
AllowHeaders: []string{"Origin", "Authorization", "Content-Type", "X-Requested-With", "*"},
// 暴露的请求头
ExposeHeaders: []string{"Content-Type"},
// 凭证共享
AllowCredentials: true,
// 允许跨域的源网站
AllowOriginFunc: func(origin string) bool {
return true
},
// 超时时间设定
MaxAge: 24 * time.Hour,
})
}

25
router/router.go Normal file
View File

@ -0,0 +1,25 @@
package router
import (
"api/config"
"api/utils"
"log"
"net/http"
"time"
)
func InitGlobalVariable() {
// 初始化 Viper
utils.InitViper()
}
func Server() *http.Server {
serverPort := config.Cfg.Server.ServerPort
log.Printf("服务启动于 %s 端口", serverPort)
return &http.Server{
Addr: serverPort,
Handler: ServerRouter(),
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}
}

23
router/server_router.go Normal file
View File

@ -0,0 +1,23 @@
package router
import (
"api/config"
"api/router/middleware"
"github.com/gin-gonic/gin"
"net/http"
)
func ServerRouter() http.Handler {
gin.SetMode(config.Cfg.Server.AppMode)
r := gin.New()
r.SetTrustedProxies([]string{"*"})
r.Use(middleware.Cors()) // 跨域中间件
// 无需鉴权的接口
base := r.Group("/api")
{
base.GET("/getHeaders", networkApi.GetHeaders)
}
return r
}

9
router/z_enter.go Normal file
View File

@ -0,0 +1,9 @@
package router
import (
"api/api/network/server"
)
var (
networkApi server.NetWorkApi
)