Jake
Jake

Reputation: 21

Go Template.ParseFiles and filepath.Join

I am trying to load an html file from a directory and I am getting the error "open templates: no such file or directory"

My directory structure is below

/Users/{username}/go/src/app main.go

/Users/{username}/go/src/app/templates mytemplate.html

The error is coming from the line below

template.Must(template.ParseFiles(filepath.Join("templates", "mytemplate.html")))

I am new to go and just trying to get a feel for the syntax.

EDIT 1

I am building the project using the "go build" command and executing it out of the "app" directory shown above.

$GOROOT = /usr/local/go $GOPATH = /Users/{username}/go

I also updated the directory structure to integrate the $GOPATH

Upvotes: 1

Views: 2414

Answers (2)

LenW
LenW

Reputation: 3096

Check the working directory that your program has at runtime with

dir, _ := os.Getwd()
fmt.Println(dir)

Then you can use that to get the right path for the templates

template.Must(template.ParseFiles(filepath.Join(dir, "templates", "mytemplate.html")))

For production use you could get the val of dir fro a config file or the environment,

ref : https://golang.org/pkg/os/#Getwd

EDIT: When you run the program make sure you are in the correct directory using cd in your terminal

Upvotes: 1

Priyanka
Priyanka

Reputation: 232

Try this,

template.Must(template.New("mytemplate.html").ParseFiles("templates/mytemplate.html"))

Upvotes: -1

Related Questions