Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I unmarshal JSON into a Go struct provided by a different piece of code?
    text
    copied!<p>I am writing a Go library that will decode JSON into a struct. The JSON has a fairly simple common schema, but I want consumers of this library to be able to decode additional fields into their own structs that embed the common struct, avoiding the need to use maps. Ideally, I'd like to decode the JSON only once.</p> <p>Currently it looks something like this. (Error handling removed for brevity.)</p> <p>The JSON:</p> <pre><code>{ "CommonField": "foo", "Url": "http://example.com", "Name": "Wolf" } </code></pre> <p>The library code:</p> <pre><code>// The base JSON request. type BaseRequest struct { CommonField string } type AllocateFn func() interface{} type HandlerFn func(interface{}) type Service struct { allocator AllocateFn handler HandlerFn } func (Service *s) someHandler(data []byte) { v := s.allocator() json.Unmarshal(data, &amp;v) s.handler(v) } </code></pre> <p>The app code:</p> <pre><code>// The extended JSON request type MyRequest struct { BaseRequest Url string Name string } func allocator() interface{} { return &amp;MyRequest{} } func handler(v interface{}) { fmt.Printf("%+v\n", v); } func main() { s := &amp;Service{allocator, handler} // Run s, eventually s.someHandler() is called } </code></pre> <p>The thing I don't like about this setup is the <code>allocator</code> function. All implementations are simply going to return a new <code>BaseRequest</code> "sub-type". In a more dynamic language I would pass the type of <code>MyRequest</code> in instead, and instantiate inside the library. Do I have a similar option in Go?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload