Skip to content

Instantly share code, notes, and snippets.

@padurean
Created January 15, 2022 13:54
Show Gist options
  • Save padurean/465472426570a38d3d1a79cb7289444c to your computer and use it in GitHub Desktop.
Save padurean/465472426570a38d3d1a79cb7289444c to your computer and use it in GitHub Desktop.
Golang enum pattern with TextMashalJSON
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