Created
January 15, 2022 13:54
-
-
Save padurean/465472426570a38d3d1a79cb7289444c to your computer and use it in GitHub Desktop.
Golang enum pattern with TextMashalJSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package task | |
import ( | |
"fmt" | |
"strings" | |
) | |
// Status ... | |
type Status int | |
// Status values | |
const ( | |
StatusUnknown Status = iota | |
StatusToDo | |
StatusInProgress | |
StatusInReview | |
StatusInTesting | |
StatusDone | |
StatusDeployed | |
) | |
// String ... | |
func (s Status) String() string { | |
return [...]string{"Unknown", "ToDo", "InProgress", "InReview", "InTesting", "Done", "Deployed"}[s] | |
} | |
// FromString ... | |
func (s *Status) FromString(str string) bool { | |
ss, ok := map[string]Status{ | |
"todo": StatusToDo, | |
"inprogress": StatusInProgress, | |
"inreview": StatusInReview, | |
"intesting": StatusInTesting, | |
"done": StatusDone, | |
"deployed": StatusDeployed, | |
}[strings.ToLower(str)] | |
if ok { | |
*s = ss | |
} | |
return ok | |
} | |
// UnmarshalText ... | |
func (s *Status) UnmarshalText(text []byte) error { | |
if s.FromString(string(text)) { | |
return nil | |
} | |
return fmt.Errorf("unknown status: %s", text) | |
} | |
// MarshalText ... | |
func (s Status) MarshalText() ([]byte, error) { | |
return []byte(s.String()), nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment