envloader

package
v1.0.9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 10, 2026 License: MPL-2.0 Imports: 5 Imported by: 0

Documentation

Overview

Copyright 2025 Raywall Malheiros de Souza Licensed under the Mozilla Public License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

https://www.mozilla.org/en-US/MPL/2.0/

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Package envloader fornece um utilitário simples para carregar variáveis de ambiente diretamente para campos de uma struct Go, incluindo suporte para tags de ambiente (`env`) e valores padrão (`envDefault`).

Visão Geral: O `envloader` simplifica a gestão de configurações em aplicações Go. Ele utiliza reflection para inspecionar a struct de configuração e mapear automaticamente variáveis de ambiente para os campos tipados. Suporta tipos básicos como string, int, uint, bool e float, além de structs aninhadas (incluindo ponteiros para structs).

Funcionalidades Principais: - Mapeamento por Tag: Usa a tag `env:"VAR_NAME"` para encontrar a variável. - Valores Padrão: Usa a tag `envDefault:"value"` se a variável não estiver definida. - Suporte a Aninhamento: Processa structs aninhadas e ponteiros para structs. - Tratamento de Erros Tipados: Retorna erros específicos para configurações inválidas ou conversões de tipo.

Exemplos de Uso:

Exemplo Básico: Demonstra como carregar uma configuração simples.

// Assumindo que a variável de ambiente DB_HOST está definida como "localhost"
type Config struct {
    DBHost string `env:"DB_HOST"`
    DBPort int    `env:"DB_PORT" envDefault:"5432"`
}

var cfg Config
if err := envloader.Load(&cfg); err != nil {
    log.Fatal(err)
}

fmt.Printf("Host: %s, Port: %d\n", cfg.DBHost, cfg.DBPort) // Output: Host: localhost, Port: 5432

Exemplo com Struct Aninhada:

type ServerConfig struct {
    Host string `env:"SERVER_HOST"`
}
type AppConfig struct {
    Server ServerConfig
}

// Assumindo SERVER_HOST="0.0.0.0" está definido
var appCfg AppConfig
if err := envloader.Load(&appCfg); err != nil {
    log.Fatal(err)
}

Configuração: O pacote requer que a função `Load` receba um ponteiro para a struct de configuração. As variáveis de ambiente devem estar definidas no sistema operacional antes da execução de `Load`.

Copyright 2025 Raywall Malheiros de Souza Licensed under the Mozilla Public License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

https://www.mozilla.org/en-US/MPL/2.0/

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2025 Raywall Malheiros de Souza Licensed under the Mozilla Public License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

https://www.mozilla.org/en-US/MPL/2.0/

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Load

func Load(config interface{}) error

Load preenche uma struct com valores de variáveis de ambiente.

A função itera sobre os campos da struct e usa as tags "env" para buscar o valor correspondente. Se a variável de ambiente não existir, o valor de "envDefault" será usado.

Parâmetros:

config: Um ponteiro para a struct que será preenchida. Deve ser um ponteiro para struct.

Retorna:

error: Retorna nil em caso de sucesso ou um erro tipado (`InvalidConfigError`,
  `FieldError`) se a operação falhar.

Exemplo:

cfg := &Config{}
err := Load(cfg)

Erros:

  • InvalidConfigError: Se 'config' não for um ponteiro para struct.
  • FieldError: Se houver falha na conversão de tipo de uma variável de ambiente para o tipo do campo.

func MustLoad

func MustLoad(config interface{})

MustLoad é similar ao Load, mas provoca um panic em caso de erro.

Deve ser usado para configurações essenciais onde a falha na inicialização do programa é inaceitável.

Parâmetros:

config: Um ponteiro para a struct de configuração.

Exemplo:

cfg := &Config{}
MustLoad(cfg) // O programa termina se houver erro

Types

type FieldError

type FieldError struct {
	// FieldName é o nome do campo da struct (ex: "Port").
	FieldName string
	// EnvVar é o nome da variável de ambiente (ex: "APP_PORT").
	EnvVar string
	// Value é o valor bruto da variável de ambiente que causou o erro (ex: "abc").
	Value string
	// Err é o erro original encapsulado (ex: *strconv.NumError).
	Err error
}

FieldError é retornado quando ocorre um erro ao tentar definir o valor de um campo específico da struct.

Tipicamente encapsula um erro de conversão de tipo (`strconv`) ou um `UnsupportedTypeError`.

func (*FieldError) Error

func (e *FieldError) Error() string

Error retorna uma mensagem detalhada do erro de campo.

func (*FieldError) Unwrap

func (e *FieldError) Unwrap() error

Unwrap retorna o erro original que causou o FieldError, implementando a interface `Unwrap` para Go 1.13+.

type InvalidConfigError

type InvalidConfigError struct {
	// Value é o tipo refletido que foi fornecido (ex: reflect.String, reflect.Ptr).
	Value reflect.Type
}

InvalidConfigError é retornado quando a função Load recebe um argumento 'config' que não é um ponteiro para uma struct.

func (*InvalidConfigError) Error

func (e *InvalidConfigError) Error() string

Error retorna uma mensagem formatada indicando o tipo de argumento inválido.

O método é implementado para satisfazer a interface Go `error`.

Exemplo de Retorno: "envloader: config must be a pointer to struct, got string"

type UnsupportedTypeError

type UnsupportedTypeError struct {
	// Type é o tipo refletido do campo não suportado.
	Type reflect.Type
}

UnsupportedTypeError é retornado quando o tipo do campo da struct (ex: map, slice, interface) não é suportado pelo `envloader` para conversão.

func (*UnsupportedTypeError) Error

func (e *UnsupportedTypeError) Error() string

Error retorna uma mensagem indicando o tipo que não possui suporte.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL