Reputation: 6783
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?
Upvotes: 0
Views: 119
Reputation: 40789
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)
}
}
Upvotes: 1