无法在生产版本中使用 LoadHTMLGlob 加载 html 文件。它正在开发中

Can't load html file with LoadHTMLGlob in production build. It's working in development

我在我的 rest-API 服务中使用 Go Gin 包。为了添加一些数据,我使用了 HTML 文件来提交带有数据的表单。在开发中,它工作正常,但在生产构建服务器中不工作,如果我评论 'LoadHTMLGlob' 阻止服务器再次工作。我认为 'LoadHTMLGlob' 无法加载 HTML。请帮助解决这个问题。

我的main.go文件:

package main

import (
    "ct-merchant-api/Config"
    "ct-merchant-api/Routes"
    "fmt"
    "github.com/jinzhu/gorm"
)
var err error

func main() {
    Config.DB, err = gorm.Open("mysql", Config.DbURL(Config.BuildDBConfig()))

    if err != nil {
        fmt.Println("Status:", err)
    }
    defer Config.DB.Close()

    r := Routes.SetupRouter()
    
    // Load HTML   
    r.LoadHTMLGlob("templates/*")
    
    //running
    runningPort := Config.GetServerInfo()
    _ = r.Run(":" + runningPort.ServerPort)
}

路由文件:

package Routes

import (
    "ct-merchant-api/Controllers/Referral"
    "github.com/gin-contrib/cors"
    "github.com/gin-gonic/gin"
    "net/http"
)

func SetupRouter() *gin.Engine {
    api := gin.Default()
    config := cors.DefaultConfig()
    config.AllowAllOrigins = true
    config.AllowCredentials = true
    config.AddAllowHeaders("authorization")
    api.Use(cors.New(config))

    api.GET("/", func(c *gin.Context) {
        c.String(http.StatusOK, "Welcome to GO-rib Server")
    })

    api.GET("/referral/:merchantId", Referral.LeadForm)
    api.POST("/add-lead", Referral.LeadAdd)

    return api
}

项目结构:

├── go.mod
├── go.sum
├── main.go
├── README.md
├── Routes
│   ── Routes.go
└── templates
|   ── lead-add-response.html
|   ── referral.html

为了部署,我在 /lib/systemd/system

中创建了一个服务 go-web-api.service

go-web-api.service 文件中:

[Unit]
Description=goweb

[Service]
Type=simple
Restart=always
RestartSec=5s
ExecStart={my_project_build_file_path}

[Install]
WantedBy=multi-user.target

您需要将WorkingDirectory添加到您的系统文件

[Service]
Type=simple
Restart=always
RestartSec=5s
WorkingDirectory=/path/to/your/project //add this line
ExecStart={my_project_build_file_path}