In my application I need make two different REST request containing JSON as payload. Now for two different API basic block of JSON contain common structure as below
{
"request": {
"data": {
"Object": [
{
<Payload based on API>
}
]
}
}
}
To implement this I have written below code in two different packages
package auth
type ReqJSONAuth struct {
Request struct {
Data struct {
Object []Object `json:"Object"`
} `json:"data"`
} `json:"request"`
}
type Object struct {
User User `json:"user"`
}
type User struct {
CustomerID string //`json:"customerid"`
IPAddress string `json:"pbxaddress"`
NoOfUsers string //`json:"noofusers"`
}
func (j *ReqJSON) User() []User { return j.Request.Data.Object.User }
func (j *ReqJSON) SetUsers(u []User) { j.Request.Data.Object.User = u }
func main() {
var j ReqJSON
j.SetUser(User{
UserID: "_id",
IPAddr: "1.1.1.1",
Noofusers: "100",
Qos: "34",
ID: "kldjflkdfjlkdjfkld",
Domain: "xyz.com",
})
b, err := json.MarshalIndent(j, "", " ")
fmt.Println(err, string(b))
}
package metadata
type ReqJSONMeta struct {
Request struct {
Data struct {
Object []Object `json:"Object"`
} `json:"data"`
} `json:"request"`
}
type Object struct {
Meta Meta `json:"metadata"`
}
type Meta struct {
CustomerID string `json:"customerId"`
FilePath string `json:"filePath"`
FileName string `json:"fileName"`
}
func (j *ReqJSONMeta) User() []User { return j.Request.Data.Object.User }
func (j *ReqJSONMeta) SetUsers(u []User) { j.Request.Data.Object.User = u }
The above code works but I am want to refactor to make it more clean and generic so that we can add more API in future in current framework. How I can achieve the same.