samber / mo

🦄 Monads and popular FP abstractions, powered by Go 1.18+ Generics (Option, Result, Either...)
https://pkg.go.dev/github.com/samber/mo
MIT License
2.61k stars 85 forks source link

Add MarshalJSON for Result[T] #32

Closed joel-u410 closed 1 year ago

joel-u410 commented 1 year ago

I thought it would be useful to support JSON marshaling for Result[T]. This would likely be used within the context of building a JSON-RPC service, so I implemented it here in a way that generally conforms to the JSON-RPC spec.

There is one notable exception, the spec requires a code field in an error object that indicates the type of error that occurred, and this information is not readily available from an error in Go. So I left that out, resulting in slight nonconformance to the spec.

I had thought about always including something like code: -32000 as a general server error, but it seemed better to me to leave it out rather than inserting something that may or may not be correct in all situations.

If you think this is too opinionated a way to represent a Result[T] in JSON, feel free to reject & close this PR. 🙂

samber commented 1 year ago

Could you please add the unmarshaler?

joel-u410 commented 1 year ago

Yep, will do!

joel-u410 commented 1 year ago

The reason I hadn't originally implemented unmarshalling is because it's lossy going to JSON -- the error type is lost (only the message is marshaled).

Are you ok with an unmarshal implementation that simply uses errors.New to construct a generic error object for the Err case?

joel-u410 commented 1 year ago

Here's a first pass at implementing UnmarshalJSON -- please let me know if you agree with the implementation, particularly around malformed inputs (e.g. both result and error populated --> Err)

samber commented 1 year ago

Ok, I understand the limit of unmarshaling.

Using errors.New looks like a good workaround.