Documentation
¶
Overview ¶
Package env provides functions for loading structs from environment variables.
Index ¶
- func MustParse(v any, opts ...ParserOption)
- func MustParseFor[T any](opts ...ParserOption) T
- func Parse(v any, opts ...ParserOption) error
- func ParseFor[T any](opts ...ParserOption) (T, error)
- func Print(v any, opts ...ParserOption)
- func Register[T any](fn CustomParserFunc)
- type CustomParserFunc
- type Deferred
- type Field
- type Parser
- type ParserOption
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func MustParse ¶
func MustParse(v any, opts ...ParserOption)
Parse is a convenience function for calling Parse that panics if an error is encountered.
func MustParseFor ¶
func MustParseFor[T any](opts ...ParserOption) T
MustParseFor is a convenience function for calling ParseFor that panics if an error is encountered.
Example ¶
package main
import (
"fmt"
"os"
"go.chrisrx.dev/x/env"
)
func main() {
_ = os.Setenv("MYSERVICE_ADDR", ":8443")
opts := env.MustParseFor[struct {
Addr string `env:"ADDR" default:":8080" validate:"split_addr(self).port > 1024"`
}](env.RootPrefix("MYSERVICE"))
fmt.Printf("MYSERVICE_ADDR: %q\n", opts.Addr)
}
Output: MYSERVICE_ADDR: ":8443"
Example (FileServer) ¶
package main
import (
"fmt"
"log"
"net"
"net/http"
"time"
"go.chrisrx.dev/x/context"
"go.chrisrx.dev/x/env"
)
var opts = env.MustParseFor[struct {
Addr string `env:"ADDR" default:":8080" validate:"split_addr().port > 1024"`
Dir http.Dir `env:"DIR" $default:"tempdir()"`
ReadTimeout time.Duration `env:"TIMEOUT" default:"2m"`
WriteTimeout time.Duration `env:"WRITE_TIMEOUT" default:"30s"`
MaxHeaderBytes int `env:"MAX_HEADER_BYTES" $default:"1 << 20"`
}](env.RootPrefix("FILESERVER"))
func main() {
ctx := context.Shutdown()
s := &http.Server{
Addr: opts.Addr,
Handler: http.FileServer(opts.Dir),
ReadTimeout: opts.ReadTimeout,
WriteTimeout: opts.WriteTimeout,
MaxHeaderBytes: opts.MaxHeaderBytes,
BaseContext: func(net.Listener) context.Context { return ctx },
}
ctx.AddHandler(func() {
fmt.Println("\rCTRL+C pressed, attempting graceful shutdown ...")
if err := s.Shutdown(ctx); err != nil {
panic(err)
}
})
log.Printf("serving %s at %s ...\n", opts.Dir, opts.Addr)
if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatal(err)
}
}
func Parse ¶
func Parse(v any, opts ...ParserOption) error
Parse parses tags for the provided struct and sets values from environment variables. It will only set values that have the `env` tag. Value must be a pointer value to allow setting values.
func ParseFor ¶
func ParseFor[T any](opts ...ParserOption) (T, error)
ParseFor parses tags for the provided struct and sets values from environment variables. It accepts a struct or pointer to a struct. If a non-pointer, a copy of the struct with values set will be returned.
func Print ¶
func Print(v any, opts ...ParserOption)
Print prints a representation of a struct to standard output. It using the same rules as Parser.
Example ¶
package main
import (
"net/http"
"time"
"go.chrisrx.dev/x/env"
)
func main() {
env.Print(env.MustParseFor[struct {
Addr string `env:"ADDR" default:":8080" validate:"split_addr(self).port > 1024"`
Dir http.Dir `env:"DIR" $default:"tempdir()"`
ReadTimeout time.Duration `env:"TIMEOUT" default:"2m"`
WriteTimeout time.Duration `env:"WRITE_TIMEOUT" default:"30s"`
MaxHeaderBytes int `env:"MAX_HEADER_BYTES" $default:"1 << 20"`
}]())
}
Output: Addr{ env=ADDR default=:8080 value=:8080 } Dir{ env=DIR value=/tmp } ReadTimeout{ env=TIMEOUT default=2m value=2m0s } WriteTimeout{ env=WRITE_TIMEOUT default=30s value=30s } MaxHeaderBytes{ env=MAX_HEADER_BYTES value=1048576 }
func Register ¶
func Register[T any](fn CustomParserFunc)
Register registers a custom parser with the provided type parameter. The type parameter must be a non-pointer type, however, registering a type will match for parsing for both the pointer and non-pointer of the type.
Types ¶
type CustomParserFunc ¶
CustomParserFunc is the function signature for a custom type parser.
type Deferred ¶
type Deferred bool
Deferred is a special type used in fields to configure calling methods on structs after parsing is done.
type Field ¶
type Field struct {
Name string
Anonymous bool
Exported bool
// tags
Env string
Default string
DefaultExpr string
Validate string
Separator string
Required bool
Layout string
DeferredMethod string
// contains filtered or unexported fields
}
Field represents a parsed struct field.
type Parser ¶
type Parser struct {
DisableAutoPrefix bool
RootPrefix string
RequireTagged bool
// contains filtered or unexported fields
}
Parser is an environment variable parser for structs.
func NewParser ¶
func NewParser(opts ...ParserOption) *Parser
NewParser constructs a new Parser using the provided options.
type ParserOption ¶
type ParserOption func(*Parser)
func DisableAutoPrefix ¶
func DisableAutoPrefix() ParserOption
DisableAutoPrefix is an option for Parser that disables the auto-prefix feature.
func RequireTagged ¶
func RequireTagged() ParserOption
RequireTagged is an option for Parser that makes all struct fields required. This applies regardless of whether the `env` tag is set.
func RootPrefix ¶
func RootPrefix(prefix string) ParserOption
RootPrefix is an option for Parser that sets a root prefix for environment variable names.