template.ParseFiles 的问题

我有以下 http.Handle 函数(简化):


func loginHandler(w http.ResponseWriter, r *http.Request) {


        cwd, _ := os.Getwd()

        t, err := template.ParseFiles(filepath.Join(cwd, "./views/login.html"))


        if err != nil {

            fmt.Fprintf(w, "503 - Error")

            fmt.Println(err)

        } else {

            t.Execute(w, nil)

        }


}

它在使用时按预期工作go build main.go,但是 - 运行后go install,我收到一个错误,它找不到文件(因为它现在被编译到/bin/<appname>(没有视图文件夹的地方)。除了将视图文件夹添加到/bin目录或硬编码路径,我怎样才能template.ParseFiles()找到正确的路径?


是否有一些标准方法可以包含用于编译程序的“静态”资源?


慕妹3146593
浏览 160回答 1
1回答

皈依舞

没有标准方法可以为编译程序包含静态资源;然而,一种常见的约定是将配置存储在环境变量中。例如,在运行您的应用程序时,将预期的环境变量放入环境中:$> TEMPLATE_VIEWS=/var/local/app/views myapp在您的代码中,您会找到文件夹:func loginHandler(w http.ResponseWriter, r *http.Request) {&nbsp; &nbsp; t, err := template.ParseFiles(filepath.Join(os.Getenv("TEMPLATE_VIEWS"), "login.html"))&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Fprintf(w, "503 - Error")&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(err)&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; t.Execute(w, nil)&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go