Constructors & Funcs
Constructors must validate all required dependencies using enforce helpers and return pointer
types. Only to be used in the context of when being called from a cmd package.
New
- Prefer
NewX()constructors over global initialisation unless it’s the only constructor in the package then it will be written asNew().
Enforce
- Not nil values →
enforce.NotNil() - Boolean conditions →
enforce.True() - Equality / inequality →
enforce.Equal()orenforce.NotEqual() - Absence of error →
enforce.NoError()
These helpers provide simple runtime guarantees and will exit the program with a helpful message if a condition fails.
This package can be found in github.com/ainsleydev/webkit/pkg.
Example:
1func NewGenerator(fs afero.Fs, manifest *manifest.Tracker, printer *printer.Console) *FileGenerator {
2 enforce.NotNil(fs, "file system is required")
3 enforce.NotNil(manifest, "manifest is required")
4 enforce.NotNil(printer, "printer is required")
5
6 return &FileGenerator{
7 Printer: printer,
8 fs: fs,
9 manifest: manifest,
10 }
11}
Context
Use context.Context as the first parameter for functions that perform I/O or can be cancelled.
Example:
1 func Run(ctx context.Context, cmd Command) (Result, error) {
2 select {
3 case <-ctx.Done():
4 return Result{}, ctx.Err()
5 default:
6 // Execute command
7 }
8}