Skip to content

Instantly share code, notes, and snippets.

@0xdevalias
Created July 17, 2018 01:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save 0xdevalias/efe5848748dec55646b6c847c26f1e11 to your computer and use it in GitHub Desktop.
Save 0xdevalias/efe5848748dec55646b6c847c26f1e11 to your computer and use it in GitHub Desktop.
Golang application state pattern boilerplate/reference code
[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"
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
}
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