duanan2732
duanan2732
2016-03-29 02:55

template.ParseFiles问题

  • IT行业问题
  • 计算机技术
  • it技术
  • 编程语言问答
  • 互联网问答
已采纳

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条回答

  • dongxi6897 dongxi6897 5年前

    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)
        }
    }
    
    点赞 评论 复制链接分享

为你推荐