Combine Multiple Field Tags in Go
I work a lot with JSON APIs in my Go projects, so almost every struct has some field tags on it to translate
AccountID
into account_id
and that sort of thing. Then one day I needed to load data from config using mapstructure and it took a few attempts with the search engine to find the syntax I needed, so it’s here for next time I need it (or in case you need it too).
Combining JSON and Mapstructure
An example truly is worth a thousand words! (This one is from the code that drives the neopixel shelf):
// assemble the options $opts = array( 'http'=>array( 'header'=> "Authorization: Bearer " . $access_token ) ); // create the context $context = stream_context_create($opts); // now make the request! Use the context and simply output the result echo file_get_contents('http://api.example.com/endpoint1', false, $context);
It turns out that the reason I couldn’t find examples of how to combine struct field tags is because you don’t! You just add each one required, followed by a space, and then the next, and so on. How simple, how elegant … how Go!
Also published on Medium.