routers.go 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package routers
  2. import (
  3. "fmt"
  4. "github.com/gin-gonic/gin"
  5. "github.com/swaggo/gin-swagger"
  6. "github.com/swaggo/gin-swagger/swaggerFiles"
  7. _ "lttc-go-adm-znaf/docs"
  8. "lttc-go-adm-znaf/routers/api/v1"
  9. "net/http"
  10. "strings"
  11. )
  12. // 初始化路由
  13. func InitRouter() *gin.Engine {
  14. r := gin.New()
  15. r.Use(gin.Logger())
  16. r.Use(gin.Recovery())
  17. r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
  18. api := r.Group("api/v1")
  19. api.Use()
  20. {
  21. api.GET("/index", v1.Index)
  22. api.GET("/getAllVehicles", v1.GetAllVehicles)
  23. }
  24. return r
  25. }
  26. // 跨域
  27. func Cors() gin.HandlerFunc {
  28. return func(c *gin.Context) {
  29. method := c.Request.Method //请求方法
  30. origin := c.Request.Header.Get("Origin") //请求头部
  31. var headerKeys []string // 声明请求头keys
  32. for k := range c.Request.Header {
  33. headerKeys = append(headerKeys, k)
  34. }
  35. headerStr := strings.Join(headerKeys, ", ")
  36. if headerStr != "" {
  37. headerStr = fmt.Sprintf("access-control-allow-origin, access-control-allow-headers, %s", headerStr)
  38. } else {
  39. headerStr = "access-control-allow-origin, access-control-allow-headers"
  40. }
  41. if origin != "" {
  42. c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
  43. c.Header("Access-Control-Allow-Origin", "*") // 这是允许访问所有域
  44. c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE") //服务器支持的所有跨域请求的方法,为了避免浏览次请求的多次'预检'请求
  45. // header的类型
  46. c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma")
  47. // 允许跨域设置 可以返回其他子段
  48. c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar") // 跨域关键设置 让浏览器可以解析
  49. c.Header("Access-Control-Max-Age", "172800") // 缓存请求信息 单位为秒
  50. c.Header("Access-Control-Allow-Credentials", "false") // 跨域请求是否需要带cookie信息 默认设置为true
  51. c.Set("content-type", "application/json") // 设置返回格式是json
  52. }
  53. //放行所有OPTIONS方法
  54. if method == "OPTIONS" {
  55. c.JSON(http.StatusOK, "Options Request!")
  56. }
  57. // 处理请求
  58. c.Next() // 处理请求
  59. }
  60. }