main.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package main
  2. import (
  3. "demo/configs"
  4. "demo/router"
  5. "demo/util/templatefunc"
  6. "github.com/gin-gonic/gin"
  7. "net/http"
  8. "net/http/httputil"
  9. "net/url"
  10. )
  11. func init() {
  12. configs.ConfigInit()
  13. }
  14. func main() {
  15. runGin()
  16. //Test()
  17. }
  18. // 接口前缀
  19. func runGin() {
  20. Router := gin.Default()
  21. router.TestRouth(Router.Group("/"))
  22. // 重定向 /back 及其子路径到指定 IP 地址
  23. apiGroup := Router.Group(router.Prefix)
  24. Router.SetFuncMap(templatefunc.BaseTemplateFunc())
  25. //加载模板
  26. Router.LoadHTMLGlob("file/static/*")
  27. apiGroup.StaticFS("/static", http.Dir("file/resources"))
  28. apiGroup.StaticFS("/assets", http.Dir("file/assets"))
  29. proxy(Router)
  30. router.InitRouter(apiGroup)
  31. router.InitAuthority(Router)
  32. Router.Run(":8182")
  33. }
  34. func proxy(Router *gin.Engine) {
  35. proxy := func(target string) gin.HandlerFunc {
  36. return func(c *gin.Context) {
  37. targetUrl, err := url.Parse(target)
  38. if err != nil {
  39. c.JSON(http.StatusInternalServerError, gin.H{"error": "Invalid target URL"})
  40. return
  41. }
  42. proxy := httputil.NewSingleHostReverseProxy(targetUrl)
  43. proxy.ServeHTTP(c.Writer, c.Request)
  44. }
  45. }
  46. // 将所有未定义的路径转发到其他 IP
  47. Router.NoRoute(proxy("http://127.0.0.1:12306"))
  48. }