Skip to content

Instantly share code, notes, and snippets.

@kailashyogeshwar85
Created September 2, 2021 14:26
Show Gist options
  • Save kailashyogeshwar85/e4262d86485e7cd0a9e077af83e014fb to your computer and use it in GitHub Desktop.
Save kailashyogeshwar85/e4262d86485e7cd0a9e077af83e014fb to your computer and use it in GitHub Desktop.
package engine
import (
"encoding/json"
"reflect"
)
type Side int
// 0 = sell 1 = buy
const (
Sell Side = iota
Buy
)
func (s Side) String() string {
if s == Buy {
return "buy"
}
return "sell"
}
// implement Marshalling and Unmarshalling
// will convert struct to json
func (s Side) MarshalJSON() ([]byte, error) {
return []byte(`"` + s.String() + `"`), nil
}
// will convert json to struct
func (s *Side) UnmarshalJSON(data []byte) error {
switch string(data) {
case `"buy"`:
*s = Buy
case `"sell"`:
*s = Sell
default:
return &json.UnsupportedValueError{
Value: reflect.New(reflect.TypeOf(data)),
Str: string(data),
}
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment