I've just started working with GO and am creating a simple web interface. I have a working GO server, an HTML template called "survey.gtpl" which is served up by the server as expected, and a logo I would like displayed on the web page. No matter where I place the image within the workspace directory structure or what I put as the src path, the image will not load.
Here is the current directory structure:
+ workspace
+ bin
server.exe
+ src
+ github.com
+ cwrighta70
+ web
server.go
LogoColor.jpg
survey.gtpl
And here is the path within the "survey.gtpl" template"
<img src = "LogoColor.jpg" alt="Logo" width="789px" height="182px">
I've tried putting the image in it's own directory within the workspace, like workspace/img/LogoColor.jpg
. I've also tried putting it in with the web server executable in workspace/bin/LogoColor.jpg
. All I get in the browser is the Alt text.
Any help is greatly appreciated!
Okay, so if found a couple different ways to do this. First, my actual solution was to port my app to a CGI rather than a Go Web Server. This took away the need to serve up assets separately.
However, for those who have a Go web server and need to get this figured out, here's how I did it. I placed all of my resources (i.e., images, stylesheets, etc) in a "resources" directory at the root of where the app was being run, then added a HandleFunc
for this URL in the main as shown here:
router := http.NewServeMux()
router.HandleFunc(getURL("/view/"), viewHandler)
router.HandleFunc(getURL("/resources/"), serveAssets)
Then, the serveAssets
function attempts to open each resource, and if successful calls ServeContent
as shown:
func serveAssets(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
file, err := os.Open(docRoot + r.URL.String())
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
modeTime := time.Now()
http.ServeContent(w, r, docRoon+r.URL.String(), modeTime, file)
}
That should do it!