JSON を構造体にデコードする Go ライブラリを作成しています。JSON にはかなり単純な共通スキーマがありますが、このライブラリの利用者が追加フィールドを共通構造体を埋め込んだ独自の構造体にデコードできるようにして、マップを使用する必要がないようにしたいと考えています。理想的には、JSON を 1 回だけデコードしたいと考えています。
現在はこんな感じです。(簡潔にするためにエラー処理を削除しました。)
JSON:
{ "CommonField": "foo",
"Url": "http://example.com",
"Name": "Wolf" }
ライブラリ コード:
// 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, &v)
s.handler(v)
}
アプリのコード:
// The extended JSON request
type MyRequest struct {
BaseRequest
Url string
Name string
}
func allocator() interface{} {
return &MyRequest{}
}
func handler(v interface{}) {
fmt.Printf("%+v\n", v);
}
func main() {
s := &Service{allocator, handler}
// Run s, eventually s.someHandler() is called
}
このセットアップで気に入らないのはallocator
機能です。BaseRequest
すべての実装は、単に新しい「サブタイプ」を返すだけです。より動的な言語では、代わりに in の型を渡しMyRequest
、ライブラリ内でインスタンス化します。Goにも同様のオプションがありますか?