I’m new to Go but already exited, to practice I started to build a simple blog app, and everything is working smooth, except for the css.
I have been trying lot’s of examples for days now but it just keeps replying with a 404.
These are two of the examples I’ve tried and both examples are explained on other resources in the same way:
I use the “Build main.go and run” function inside Webstorm. I have now builded it from the terminal and ran the exec, but still the browser can’t locate the file:
GET http://localhost:8080/static/style.css 404 (Not Found)
If I use the examples from the links it’s also the same using build and the run the exec.
Edit: It’s not displaying anything at all at the moment. Just: open /Users/jschalkwijk/GolangTraining/blog/templates/header.html: no such file or directory
I do have a connection with my database and no errors in my terminal. But now it doesn’t seem to find the template files
It’s saying that there is no such file or dir, but even if I put it the system path, it say’s the same
panic: stat Users/jorn/Documents/Golang/src/github.com/jschalkwijk/GolangTraining/blog/static/style.css: no such file or directory
I’m not a professional programmer yet so I don’t really know where to look now.
Wherever you are in your directory structure when you [run your program], that becomes your root for your server.
For example:
Looking at this error
And this line in your code:
var templates, _ = filepath.Abs("../jschalkwijk/GolangTraining/blog/templates")
I would assume you were in “/Users/anydirectory/” when you started your program (that time), which means “/Users/anydirectory/” was the working directory for your program which according to the docs meant template was equal to /Users/jschalkwijk/GolangTraining/blog/templates which would probably lead nowhere useful.
I think I’d need a full view of your console output to be more sure of this, but that might be a place to start looking.
Always use absolute paths. Change them via a config file or environmental variables - e.g. os.Getenv("ASSET_DIR") - where ASSET_DIR is set to /Users/you/code/project/assets/ and not just ./assets/.
Relative paths to assets, configuration, etc. are a trap
Thanks, after some trial and error I got it to work, and also have a better understanding of the how and why!
@dfc you where right, I just didn’t fully understand what you meant @Jaytn Thanks for clarifying and the link to Todd’s lecture, this will help overcome future problems. And @toddmcleod as always thanks for your code base and quick reply, a lot of examples to work from!
I have had to change the path to:
r.PathPrefix("/GolangTraining/blog/static/css").Handler(http.StripPrefix("/GolangTraining/blog/static/css", http.FileServer(http.Dir("./GolangTraining/blog/static/css"))))
And the CSS path to:
<link href="/GolangTraining/blog/static/css/style.css" type="text/css" rel="stylesheet"/>
And then I changed directory into github.com/jschalkwijk and ran the main.go from there.