golang common structs in different namespaces

99 Views Asked by At

I have 160+ .xsd schemas and for each file I generated xsd.go files with xsdgen, but each document has common Header of CommonType.

namespace some_document

type Document struct {
    Header CommonType `xml:"header"`
        // Other fields
}


type CommonType struct {
    A  A `xml:"a"`
    B  B `xml:"b"`
    C1 C `xml:"c1"`
    C2 C `xml:"c2"`
    D  D `xml:"d"`
}

type A string

type B string

type C string

type D string

namespace any_document

type Document struct {
    Header CommonType `xml:"header"`
        // Other fields
}


type CommonType struct {
    A  A `xml:"a"`
    B  B `xml:"b"`
    C1 C `xml:"c1"`
    C2 C `xml:"c2"`
    D  D `xml:"d"`
}

type A string

type B string

type C string

type D string

Also, for each schema I create a function for building it. I want to create a function BuildHeader and reuse it in builder's functions. Is there any way to create common namespace with this type and use it instead any_document.CommonType and some_document.CommonType? I don't want to edit code generated files.

namespace common

type CommonType struct {
    A  A `xml:"a"`
    B  B `xml:"b"`
    C1 C `xml:"c1"`
    C2 C `xml:"c2"`
    D  D `xml:"d"`
}

type A string

type B string

type C string

type D string

My thoughts:

  1. extract Header in package 'common' and change CommonType to common.CommonType for each document
  2. ...?
1

There are 1 best solutions below

9
Burak Serdar On

If you are dealing with generated structures, there is no easy way of doing this. You can, however, write one function to initialize the common header and use it for all generated types, provided they are structurally identical.

package initializer

type CommonType struct {
  // Identical fields of the common type in all the packages
...
}

func NewCommonType() CommonType {
   // initialize an instance of CommonType
   return commonType
}

Then you can use:

var doc1 pkg1.Document
var doc2 pkg2.Document
...
doc1.CommonType = pkg1.CommonType(initializers.NewCommonType())
doc2.CommonType = pkg2.CommonType(initializers.NewCommonType())