Created
July 17, 2018 01:48
-
-
Save 0xdevalias/efe5848748dec55646b6c847c26f1e11 to your computer and use it in GitHub Desktop.
Golang application state pattern boilerplate/reference code
This file contains 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
[prune] | |
go-tests = true | |
unused-packages = true | |
[[constraint]] | |
name = "github.com/sirupsen/logrus" | |
version = "1.0.5" | |
[[constraint]] | |
name = "github.com/pkg/errors" | |
version = "0.8.0" | |
[[constraint]] | |
name = "github.com/hashicorp/go-multierror" | |
branch = "master" |
This file contains 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 main | |
func main() { | |
ctx := context.Background() | |
s, err := NewState(DefaultConfig()) | |
if err != nil { | |
log.WithError(err).Fatal("Failed to set up State") | |
} | |
err = s.Init(ctx) | |
if err != nil { | |
log.WithError(err).Fatal("Failed to initialize") | |
} | |
_ = s // TODO: Do things with state | |
} |
This file contains 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 main | |
import ( | |
"context" | |
"fmt" | |
"os" | |
"github.com/pkg/errors" | |
"github.com/hashicorp/go-multierror" | |
log "github.com/sirupsen/logrus" | |
) | |
type Config struct { | |
Foo string | |
} | |
type State struct { | |
Config *Config | |
} | |
const ( | |
envFoo = "FOO" | |
) | |
func DefaultConfig() *Config { | |
cfg := Config{ | |
Foo: os.Getenv(envFoo), | |
} | |
return &cfg | |
} | |
func NewState(cfg *Config) (*State, error) { | |
err := cfg.Validate() | |
if err != nil { | |
return nil, errors.Wrap(err, "NewState") | |
} | |
s := State{ | |
Config: cfg, | |
} | |
return &s, nil | |
} | |
// Validate that the config parameters are acceptable. | |
func (cfg *Config) Validate() error { | |
var err error | |
errMsg := "'%s' is a required ENV var" | |
if cfg.Foo == "" { | |
err = multierror.Append(err, fmt.Errorf(errMsg, envFoo)) | |
} | |
return errors.Wrap(err, "Validate") | |
} | |
func (s *State) Init(ctx context.Context) error { | |
var err error | |
log := log.WithField("func", "Init") | |
// TODO: Init type things | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment