loading...
Cover image for Localizing Go to JavaScript

Localizing Go to JavaScript

foresthoffman profile image Forest Hoffman Updated on ・2 min read

While working a Go backend for a side-project, I implemented a custom templating system among other things. For my project, I needed to be able to pass nonce values down to my JavaScript. I realized that keeping the data in the front-end up-to-date with the backend would require a lot of leg work. In order to save time and effort, I built the localize package.

This package takes a pre-defined Go data structure and recursively translates it to JavaScript primitives. The JavaScript that is spit back out can be used in just about any fashion, but it is designed to work best with the html/template package. Since the html/template package provides support for calling functions assigned to data passed to the template.Template.Execute() function, templates can fire off the localization process themselves. Once you have a template setup to utilize the localize package, it's a fire and forget situation. The best kind, in my opinion.

Here's a simple example of the syntax:

import(
    "github.com/foresthoffman/localize"
)

func main() {
    // Generates a new localization map with the provided data.
    dataMap, err := localize.NewMap(
        // This will tell the localizer to assign the data to
        // the "_localData" global JavaScript variable.
        "_localData",
        localize.Data{
            "motd": "Hello world, welcome to a new day!",

            // "nonce" will hold an object with an element with
            // the key, "login", and the value,
            // "LaKJIIjIOUhjbKHdBJHGkhg"
            "nonce": map[string]string{
                "login": "LaKJIIjIOUhjbKHdBJHGkhg",
            },
        },
    )

    // ...proper error handling, data manipulation, etc.
}

EDIT (08/11/19): test/template.go provides a very handy example of using localize with an actual HTTP server.

That's it! :)

Posted on by:

foresthoffman profile

Forest Hoffman

@foresthoffman

Full Stack Engineer. Golang Engineer at The Home Depot. Musings about Go, TypeScript, Node.js. My thoughts are my own.

Discussion

markdown guide