template.ParseFiles存在的问题

huangapple go评论81阅读模式
英文:

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, &quot;./views/login.html&quot;))

		if err != nil {
			fmt.Fprintf(w, &quot;503 - Error&quot;)
			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/&lt;appname&gt; (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:

$&gt; 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(&quot;TEMPLATE_VIEWS&quot;), &quot;login.html&quot;))
    if err != nil {
        fmt.Fprintf(w, &quot;503 - Error&quot;)
        fmt.Println(err)
    } else {
        t.Execute(w, nil)
    }
}

huangapple
  • 本文由 发表于 2016年3月29日 10:55:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/36274555.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定