- Part 1
- Bonuses - sometime later
Overall, this was a good exercise. I was already familiar with the
html/template pkg, but I remember how much trouble this package gave me in the past.
This challenge also led me to digging a little deeper into using
I’ll introduce some of the basics of templating I’ve learned since starting with them.
There is much to learn, but I think if you can get started with getting something on the page, the rest will come with experience and practice.
HTML templates are Go structs (template.Template). They are a type that use the HTML we write in our “template” file, they aren’t the HTML itself.
This confused me at first because I was so used to thinking of a template as the HTML file I was writing.
The file you create to hold your HTML can have any extension you want; Go doesn’t care. Just configure your editor to recognize your chosen file extension as web content or HTML, whatever you need for your editor.
I believe the *.gohtml extension is commonly used, so I use that, and I set my emacs editor to web-mode so I get proper syntax highlighting, etc.
Create the following file and test out the example below:
How do we handle partials, template hierarchy, etc? That will have to wait for another post. There is a lot to it.
json.Unmarshal vs json.Decoder
Rules of thumb:
- Use json.Decoder if your data is coming from an io.Reader stream, or you need to decode multiple values from a stream of data.
- Use json.Unmarshal if you already have the JSON data in memory.
– taken from: Stack Overflow.
If I have this correct, in this case I had already read the entire JSON file into memory with ioutil.ReadFile() and I wasn’t concerned with having to decode multiple requests with JSON, so using json.Unmarshal() was acceptable.
In other words, I was reading a single JSON file, and then I was done.
There was no need to parse something different on each http request causing concern with repeatedly allocating and releasing memory, which json.Decoder handles better.
json.Decoder - HTTP Request w/ JSON
For the sake of comparison, here is a typical use of json.Decoder in decoding JSON from an HTTP POST request body:
json.Decoder - HTTP Request w/ Form Data
It’s worth noting that there is no need to decode or unmarshal the request data coming from a form: