英文:
Problems with 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>
中,那里没有views
文件夹)。除了将views
文件夹添加到/bin
目录或硬编码路径之外,我如何让template.ParseFiles()
找到正确的路径?
是否有一种标准方法来包含用于编译程序的“静态”资源?
英文:
I have the following http.Handle function (simplified):
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)
}
}
It works as intended when using go build main.go
, however - after running go install
, I get an error that it can't find the file (as it is now compiled to /bin/<appname>
(where there is no views folder). Apart from adding a views folder to the /bin
directory or hardcoding the path, how can I get the template.ParseFiles()
to find the correct path?
Is there some standard method to include 'static' resources to be used for the comiled program?
答案1
得分: 1
没有标准的方法来为编译程序包含静态资源;然而,一个常见的约定是将配置存储在环境变量中。
例如,在运行应用程序时,将预期的环境变量放入环境中:
$> TEMPLATE_VIEWS=/var/local/app/views myapp
然后在代码中找到文件夹:
func loginHandler(w http.ResponseWriter, r *http.Request) {
t, err := template.ParseFiles(filepath.Join(os.Getenv("TEMPLATE_VIEWS"), "login.html"))
if err != nil {
fmt.Fprintf(w, "503 - Error")
fmt.Println(err)
} else {
t.Execute(w, nil)
}
}
英文:
There is no standard method to include static resources for a compiled program; however one common convention is to store configuration in environment variables.
For example, when running your app, put the expected environment variable in the environment:
$> TEMPLATE_VIEWS=/var/local/app/views myapp
And in your code you would find the folder:
func loginHandler(w http.ResponseWriter, r *http.Request) {
t, err := template.ParseFiles(filepath.Join(os.Getenv("TEMPLATE_VIEWS"), "login.html"))
if err != nil {
fmt.Fprintf(w, "503 - Error")
fmt.Println(err)
} else {
t.Execute(w, nil)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论