Skip to content
jgolangPublic

About

A faster load application configurations.

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

config Package

Overview

The config package provides a set of functions for working with JSON configuration files. It offers methods to retrieve different types of data (string, int, float, bool, etc.) from a JSON key. This is useful for applications that need to read and manage configurations stored in JSON format.

Installation

To install the config package, use the following command:

go get github.com/jgolang/config

Usage

Here’s a basic example of how to use the config package:

package main

import (
    "fmt"
    "log"
    "github.com/jgolang/config"
)

func main() {
    err := config.LoadConfigFile("config.json")
    if err != nil {
        log.Fatalf("Failed to open config file: %v", err)
    }

    appName := config.GetString("app.name")
    port := config.GetInt("server.port")
    debugMode := config.GetBool("debug")

    fmt.Printf("App Name: %s\n", appName)
    fmt.Printf("Port: %d\n", port)
    fmt.Printf("Debug Mode: %t\n", debugMode)
}

Import-time load

Importing the package loads ./config.json (FilePath + FileName), resolved against the process's current working directory, unless a --config-file=<path> argument is passed to the program (see LoadConfigFile). FilePath and FileName cannot change this load, because it runs before your code. Do not start the program from a directory that untrusted users can write to.

If the import-time load fails (for example, the file does not exist), importing the package no longer panics: the getters return zero values until a file is loaded, and AutoloadError() returns the error. To keep failing fast, check it at startup:

if err := config.AutoloadError(); err != nil {
    log.Fatalf("Failed to load config.json: %v", err)
}

To disable the import-time load, build with the config_noautoload tag and load your file explicitly with LoadConfigFile:

go build -tags config_noautoload ./...

Functions

The config package provides several functions to retrieve data from a JSON configuration file.

GetString

func GetString(key string) string

Gets a string JSON node from a JSON key.

  • key: The JSON key (e.g., foo.bar).
  • Returns: The string value associated with the JSON key.

GetInt64

func GetInt64(key string) int64

Gets an integer 64 JSON node from a JSON key.

  • key: The JSON key (e.g., foo.bar).
  • Returns: The int64 value associated with the JSON key.

GetInt

func GetInt(key string) int

Gets an integer JSON node from a JSON key.

  • key: The JSON key (e.g., foo.bar).
  • Returns: The int value associated with the JSON key.

GetFloat64

func GetFloat64(key string) float64

Gets a float 64 JSON node from a JSON key.

  • key: The JSON key (e.g., foo.bar).
  • Returns: The float64 value associated with the JSON key.

GetBool

func GetBool(key string) bool

Gets a boolean JSON node from a JSON key.

  • key: The JSON key (e.g., foo.bar).
  • Returns: The boolean value associated with the JSON key.

Get

func Get(key string) interface{}

Gets a JSON node from a JSON key.

  • key: The JSON key (e.g., foo.bar).
  • Returns: The value associated with the JSON key as an interface{}.

GetArrayMaps

func GetArrayMaps(key string) []map[string]interface{}

Gets an array JSON node from a JSON key. Returns a JSON array as a map.

  • key: The JSON key (e.g., foo.bar).
  • Returns: The JSON array as a slice of maps.

LoadConfigFile

func LoadConfigFile(name string) error

Opens a file that contains a JSON object.

  • name: The name of the JSON file.
  • Returns: An error if the file cannot be opened or parsed.

--config-file argument. By default, if the program was started with a --config-file=<path> argument, LoadConfigFile (and the import-time load) opens that path instead of name, without telling the caller. The whole value after the first = is the path. Anyone who controls the program's arguments can therefore choose the configuration file. To always load the path you pass, register the configurator with IgnoreCommandLine before loading (the import-time load runs earlier and still honors the argument; build with -tags config_noautoload to disable it):

config.RegisterConfigurator(config.JSONConfigurator{IgnoreCommandLine: true})
if err := config.LoadConfigFile("/etc/myapp/config.json"); err != nil {
    log.Fatalf("Failed to load config: %v", err)
}

If the file cannot be opened or parsed, LoadConfigFile returns the error and keeps the previously loaded configuration. While no configuration is loaded, every getter returns its zero value ("", 0, false, nil).

LoadConfigFile and RegisterConfigurator are safe to call while other goroutines read the configuration. With the built-in JSONConfigurator, each getter call sees either the previous or the new configuration; two calls in a row can straddle a reload. A custom Configurator must be safe for concurrent use itself.

Example

Here’s an example configuration file (config.json):

{
    "app": {
        "name": "MyApp"
    },
    "server": {
        "port": 8080
    },
    "debug": true
}

Using the configuration file:

package main

import (
    "fmt"
    "log"
    "github.com/jgolang/config"
)

func main() {
    err := config.LoadConfigFile("config.json")
    if err != nil {
        log.Fatalf("Failed to open config file: %v", err)
    }

    appName := config.GetString("app.name")
    port := config.GetInt("server.port")
    debugMode := config.GetBool("debug")

    fmt.Printf("App Name: %s\n", appName)
    fmt.Printf("Port: %d\n", port)
    fmt.Printf("Debug Mode: %t\n", debugMode)
}

This example demonstrates how to open a configuration file and retrieve different types of data from it using the config package.

Contributing

If you have suggestions for how We could be improved, or want to report a bug, open an issue! We'd love all and any contributions.

For more, check out the Contributing Guide.

License

This project is licensed under the MIT License.

Support

If you find this repository helpful and would like to support its development, consider making a donation. Your contributions will help ensure the continued improvement and maintenance of this repository.

Thank you for your support!

ko-fi

About

A faster load application configurations.

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages