Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 14 additions & 9 deletions money.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package monies

import (
"bytes"
"encoding/json"
"errors"
"fmt"
Expand All @@ -10,6 +9,15 @@ import (
"strings"
)

// MoneyJSON is the JSON wire format of Money. It exists as a separate
// exported type so that reflection/AST-based introspection tools (e.g.
// swaggo, jsonschema generators) can derive the correct schema — Money's
// fields are unexported and thus invisible to such tools.
type MoneyJSON struct {
Amount int64 `json:"amount"`
Currency CurrencyCode `json:"currency"`
}

var (
ErrCurrencyMismatch = errors.New("currencies mismatched")
ErrNegativeSplit = errors.New("split be must be positive")
Expand Down Expand Up @@ -82,12 +90,7 @@ func (m Money) AsMajorUnits() float64 {
}

func (m *Money) UnmarshalJSON(b []byte) error {
type moneyJSON struct {
Currency CurrencyCode `json:"currency"`
Amount int64 `json:"amount"`
}

var ref moneyJSON
var ref MoneyJSON
err := json.Unmarshal(b, &ref)
if err != nil {
return err
Expand Down Expand Up @@ -151,8 +154,10 @@ func (m Money) MarshalText() ([]byte, error) {
}

func (m Money) MarshalJSON() ([]byte, error) {
buff := bytes.NewBufferString(fmt.Sprintf(`{"amount": %d, "currency": "%s"}`, m.Amount(), m.Currency().Code))
return buff.Bytes(), nil
return json.Marshal(MoneyJSON{
Amount: m.amount,
Currency: m.currency.Code,
})
}

func (m Money) SameCurrency(om Money) bool {
Expand Down
Loading