Serving the template bundle items

Here's the TemplateBundleHandler function found in the templatebundle.go source file in the handlers folder:

func TemplateBundleHandler(env *common.Env) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var templateContentItemsBuffer bytes.Buffer
enc := gob.NewEncoder(&templateContentItemsBuffer)
m := env.TemplateSet.Bundle().Items()
err := enc.Encode(&m)
if err != nil {
log.Print("encoding err: ", err)
}
w.Header().Set("Content-Type", "application/octet-stream")
w.Write(templateContentItemsBuffer.Bytes())
})

}

The code to encode data to gob format should look familiar, it's just like how we encoded the cars slice to gob format in the Transmitting gob encoded data section from the Chapter 3, Go on the Front-End with GopherJS. Inside the TemplateBundleHandler function, we first declare templateContentItemsBuffer, of the bytes.Buffer type, which will hold the gob encoded data. We then create a new gob encoder, enc. Right after this, we'll create an m variable and assign it the value of the template bundle map. We call the Encode method of the enc object, and pass in the reference to the m map. At this point, templateContentItemsBuffer should contain the gob encoded data that represents the m map. We will write out a content-type header to specify that the server will be sending out binary data (application/octet-stream). We will then write out the binary contents of templateContentItemsBuffer by calling its Bytes method. In the Setting up the template set on the client side section of this chapter, we'll see how the client-side web application picks up the template bundle items, and utilizes it to create a template set on the client side.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.83.176