dsfsdf5646 2019-04-25 13:41
浏览 644
已采纳

如何在Golang中使用gin服务两个静态站点?

I want to create an application that will call a boolean function and depending on the result provide 1 of 2 compiled react apps as static sites.

I'm using the LoadHTMLGlob function recommended by gin and it works fine with .tmpl files like the example in thier docs. However when doing just static html with a static directory for each site nothing seems to go well.

File Structure:

├── main.go
└── sites
    ├── new
    │   ├── index.html
    │   └── static
    └── old
        ├── index.html
        └── static

Go Code:

func main() {
    r := gin.Default()
    //r.LoadHTMLFiles("sites/old/index.html", "sites/new/index.html") //doesn't complain, but can't load html
    r.LoadHTMLGlob("sites/**/*") // complains about /static being a dir on boot
    r.GET("/sites/lib", func(c *gin.Context) {
        id := c.Query("id")
        useNewSite, err := isBetaUser(id)
        if err != nil {
            c.AbortWithStatusJSON(500, err.Error())
            return
        }
        if useNewSite {
            c.HTML(http.StatusOK, "new/index.html", nil)
        } else {
            c.HTML(http.StatusOK, "old/index.html", nil)
        }
    })
    routerErr := r.Run(":8080")
    if routerErr != nil {
        panic(routerErr.Error())
    }
}

I expect that when isBetaUser comes back as true it should load the static content under sites/new otherwise load sites/old.

However loading globs produces: panic: read sites/new/static: is a directory when starting panics.

Loading the html files individually (commented out above) Runs fine, but when a request comes it panics with:

html/template: "new/index.html" is undefined

I've also string using sites/[old||new]/index.html in c.HTML

  • 写回答

2条回答 默认 最新

  • donglue8180 2019-04-25 14:55
    关注

    Try sites/**/*.html to fix the panic.

    And note that Go uses the template files' base name as the template name, so to execute a template you don't use "path/to/template.html" but "template.html". This, of course, causes a problem in your case since as explained in the documentation:

    When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results.

    To fix this you need to explicitly name your templates which you can do by using the {{ define "template_name" }} action.

    1. Open sites/new/index.html
    2. Add {{ define "new/index.html" }} as the first line
    3. Add {{ end }} as the last line
    4. Repeat for sites/old/index.html with "old/index.html" as the name.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题