优化
This commit is contained in:
30
router/middleware/cors.go
Normal file
30
router/middleware/cors.go
Normal 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
25
router/router.go
Normal 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
23
router/server_router.go
Normal 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
9
router/z_enter.go
Normal file
@ -0,0 +1,9 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"api/api/network/server"
|
||||
)
|
||||
|
||||
var (
|
||||
networkApi server.NetWorkApi
|
||||
)
|
Reference in New Issue
Block a user