I’m coming from TypeScript and want to define objects for my API responses. In TS I used
type Result<T> = { isSuccessful: true; value: T; } | { isSuccessful: false; code: string; message: string; };
In Go I started with
type ResponseResultError struct {
Code string `json:"code"`
Message string `json:"message"`
}
type ResponseResult[T any] struct {
Ok bool `json:"ok"`
Value T `json:"value"`
Error ResponseResultError `json:"error"`
}
but since Go supports tuples etc. maybe there are better solutions to solve this? How would you define “something” people can consume to either create a success response containing
{ isSuccessful: true; value: T; }
or an error response containing
{ isSuccessful: false; code: string; message: string; }
?
Or should I go for the following?
type InternalErrorResponseResult struct {
IsSuccessful bool `json:"isSuccessful"`
Code string `json:"code"`
Message string `json:"message"`
}
func NewInternalErrorResponseResult(code string, message string) InternalErrorResponseResult {
return InternalErrorResponseResult{
Code: code,
Message: message,
}
}
type OperationResponseResult[T any] struct {
IsSuccessful bool `json:"isSuccessful"`
Value T `json:"value"`
}
func NewOperationResponseResult[T any](isSuccessful bool, value T) OperationResponseResult[T] {
return OperationResponseResult[T]{
IsSuccessful: isSuccessful,
Value: value,
}
}