Your code appears high quality to me. Is the rub that you simply solely need one struct sort? If that’s the case you need to try omitEmpty:
The “omitempty” choice specifies that the sphere must be omitted from the encoding if the sphere has an empty worth, outlined as false, 0, a zero pointer, a zero interface worth, and any empty array, slice, map, or string.
You possibly can outline your struct as follows:
sort End result[T any] struct {
IsSuccessful bool `json:"isSuccessful"`
Worth *T `json:"worth,omitempty"`
Code string `json:"code,omitempty"`
Message string `json:"message,omitempty"`
}
… to the place it simply doesn’t ship the keys when they’re zero values or nil. Because it’s idiomatic to make use of err != nil
to find out whether or not one thing went improper, you would additionally doubtlessly simplify your constructor code to one thing like this when you wished:
func NewResult[T any](worth *T, err error) End result[T] {
if err != nil {
return End result[T]{
IsSuccessful: false,
Code: http.StatusText(http.StatusInternalServerError),
Message: err.Error(),
}
}
return End result[T]{
IsSuccessful: true,
Worth: worth,
}
}
As a result of once more it’s idiomatic to do resp, err := doSomething()
and it will move to simply go resp, err
into this NewResult
func for my part. Put that along with some trite check code:
sort someItem struct {
ID int
Worth string
}
func foremost() {
worth := NewResult(&someItem{23, "Whats up"}, nil)
json.NewEncoder(os.Stdout).Encode(worth)
errorValue := NewResult[someItem](nil, errors.New("Drawback contacting database."))
json.NewEncoder(os.Stdout).Encode(errorValue)
}
… will yield:
{"isSuccessful":true,"worth":{"ID":23,"Worth":"Whats up"}}
{"isSuccessful":false,"code":"Inside Server Error","message":"Drawback contacting database."}
Anyway, just a few meals for thought! You possibly can additionally push this to a perform like SendJSON[T any](worth *T, err error, w http.ResponseWriter)
. That would examine err and if nil, do one factor and if not nil do one other. Right here’s a playground hyperlink with above code: