meesterguyperson
meesterguyperson

Reputation: 1884

Golang not able to see templates in external package

I am attempting to write a reusable package in Go. I'm using a structure similar to that described here but slightly different:

/src/bitbucket.org/EXTERNAL_PROJECT_NAME/EXTERNAL_PACKAGE_NAME/...
/src/INTERNAL_PROJECT_NAME/INTERNAL_PACKAGE_NAME/...

Or should the second line be:

/src/bitbucket.org/INTERNAL_PROJECT_NAME/INTERNAL_PACKAGE_NAME/...

Everything works until I need to access a non-go file that exists in the external package. For example, I have some built in templates that I would like to be available without having to include them in my internal projects templates directory.

To that end, I have a "templates" directory in the external project where I want to house some built-in templates and a "templates" directory in my internal project where custom templates will go. But when I attempt to parse templates from the external project template directory, it can't find them.

So how would I go about indicating that I want to get the templates from the external package directory instead of the internal one? I could adjust the path to something like the following:

../../bitbucket.org/EXTERNAL_PROJECT_NAME/EXTERNAL_PACKAGE_NAME/templates/file.html

but this is obviously very clumsy and depends on individual setup, so that's not going to work. In general, if I want to reference a file in an external package instead of my internal project directory, how would I do this gracefully?

Thanks!

Upvotes: 2

Views: 837

Answers (2)

meesterguyperson
meesterguyperson

Reputation: 1884

Turns out there is a pretty simple solution. Looks something like the following:

package main

import (
    "bitbucket.org/EXTERNAL_PROJECT/EXTERNAL_PACKAGE"
    "go/build"
)

func main() {
    SrcRoot := "/src"
    PackageDir := "/bitbucket.org/EXTERNAL_PROJECT/EXTERNAL_PACKAGE"
    InternalTemplateDir := build.Default.GOPATH + SrcRoot + PackageDir + "/templates/"
}

GOROOT here provides us with the path to the directory containing all our go code. From there, I want to reference the templates directory in the package source. With InternalTemplateDir, I now have the base path from which to reference templates within the external package.

For ease of use, I will probably build a template loader that checks for a file on an internal file path first and then checks for the same file in the external package, so that any given template can be overridden by including it internally, but essential templates will all have built in versions as well.

Upvotes: 2

OneOfOne
OneOfOne

Reputation: 99225

If it's not a Go package (aka bitbucket.org/EXTERNAL_PROJECT_NAME/EXTERNAL_PACKAGE_NAME/file.go) it's not gonna work, your best bet us something like https://github.com/jteeuwen/go-bindata.

But I really think you should rethink your problem and use a different approach to it.

Upvotes: 0

Related Questions