Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
feliixx committed Apr 13, 2022
0 parents commit 6248807
Show file tree
Hide file tree
Showing 8 changed files with 604 additions and 0 deletions.
34 changes: 34 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
name: Run tests with coverage

on:
push:

jobs:
test:
runs-on: ubuntu-20.04

steps:
- name: Check out code
uses: actions/checkout@v3

- name: Set up Go
uses: actions/setup-go@v3
with:
go-version: '1.18'

- name: Lint code
uses: golangci/golangci-lint-action@v3
with:
version: v1.45.2
args: --timeout 2m0s

- name: Vet code
run: go vet ./...

- name: Run test
run: ./test.sh

- name: Upload coverage to Codecov
uses: codecov/codecov-action@v2
with:
files: ./coverage.txt
19 changes: 19 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2022 Adrien Petel

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
41 changes: 41 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
[![Go Report Card](https://goreportcard.com/badge/github.com/feliixx/boa)](https://goreportcard.com/report/github.com/feliixx/boa)
[![codecov](https://codecov.io/gh/feliixx/boa/branch/master/graph/badge.svg)](https://codecov.io/gh/feliixx/boa)
[![PkgGoDev](https://pkg.go.dev/badge/github.com/feliixx/boa)](https://pkg.go.dev/github.com/feliixx/boa)

## boa

A small configuration library for go application with a viper-like API, but with limited scope and no external dependency

It supports:

* reading a config in JSON format
* setting default



## example


```go
config := `
{
"http_server": {
"enabled": true,
"host": "127.0.0.1"
}
}`

boa.SetDefault("http_server.port", 80)

err := boa.ParseConfig(strings.NewReader(config))
if err != nil {
log.Fatal(err)
}

srvHost := boa.GetString("http_server.host")
srvPort := boa.GetInt("http_server.port")

fmt.Printf("%s:%d", srvHost, srvPort)
// Output: 127.0.0.1:80
```

33 changes: 33 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package boa_test

import (
"fmt"
"log"
"strings"

"github.com/feliixx/boa"
)

func Example() {

config := `
{
"http_server": {
"enabled": true,
"host": "127.0.0.1"
}
}`

boa.SetDefault("http_server.port", 80)

err := boa.ParseConfig(strings.NewReader(config))
if err != nil {
log.Fatal(err)
}

srvHost := boa.GetString("http_server.host")
srvPort := boa.GetInt("http_server.port")

fmt.Printf("%s:%d", srvHost, srvPort)
// Output: 127.0.0.1:80
}
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/feliixx/boa

go 1.18
184 changes: 184 additions & 0 deletions parser.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
package boa

import (
"encoding/json"
"fmt"
"io"
"reflect"
"strconv"
"strings"
)

var (
config map[string]any
defaults = map[string]any{}
)

// ParseConfig reads the config from an io.Reader.
func ParseConfig(jsonConfig io.Reader) error {

d := json.NewDecoder(jsonConfig)
d.UseNumber()

return d.Decode(&config)
}

// SetDefault set the default value for this key.
func SetDefault(key string, value any) {

switch reflect.TypeOf(value).Kind() {

case reflect.Int,
reflect.Int32,
reflect.Int64,
reflect.Uint,
reflect.Uint32,
reflect.Uint64:
defaults[key] = json.Number(fmt.Sprintf("%d", value))

case reflect.Float64:
defaults[key] = json.Number(strconv.FormatFloat(value.(float64), 'g', -1, 64))
default:
defaults[key] = value
}

}

// GetString returns the value associated with the key as a string.
func GetString(key string) string {
return cast[string](getValue(key))
}

// GetBool returns the value associated with the key as a bool.
func GetBool(key string) bool {
return cast[bool](getValue(key))
}

// GetInt returns the value associated with the key as an int.
func GetInt(key string) int {

n := cast[json.Number](getValue(key))
v, err := strconv.ParseInt(string(n), 10, 64)
if err != nil {
panic("Can't parse number '%s' as an int")
}
return int(v)
}

// GetInt32 returns the value associated with the key as an int32
func GetInt32(key string) int32 {
n := cast[json.Number](getValue(key))
v, err := strconv.ParseInt(string(n), 10, 32)
if err != nil {
panic("Can't parse number '%s' as an int32")
}
return int32(v)
}

// GetInt64 returns the value associated with the key as an int64.
func GetInt64(key string) int64 {
n := cast[json.Number](getValue(key))
v, err := strconv.ParseInt(string(n), 10, 64)
if err != nil {
panic("Can't parse number '%s' as an int64")
}
return v
}

// GetUint returns the value associated with the key as an uint.
func GetUint(key string) uint {
n := cast[json.Number](getValue(key))
v, err := strconv.ParseUint(string(n), 10, 64)
if err != nil {
panic("Can't parse number '%s' as an uint")
}
return uint(v)
}

// GetUint32 returns the value associated with the key as an uint32.
func GetUint32(key string) uint32 {
n := cast[json.Number](getValue(key))
v, err := strconv.ParseUint(string(n), 10, 32)
if err != nil {
panic("Can't parse number '%s' as an uint32")
}
return uint32(v)
}

// GetUint64 returns the value associated with the key as an uint64.
func GetUint64(key string) uint64 {
n := cast[json.Number](getValue(key))
v, err := strconv.ParseUint(string(n), 10, 64)
if err != nil {
panic("Can't parse number '%s' as an uint64")
}
return uint64(v)
}

// GetFloat64 returns the value associated with the key as a float64.
func GetFloat64(key string) float64 {
n := cast[json.Number](getValue(key))
v, err := strconv.ParseFloat(string(n), 64)
if err != nil {
panic("Can't parse number '%s' as a float64")
}
return v
}

// GetAny returns any value associated with the key.
func GetAny(key string) any {
return getValue(key)
}

func getValue(key string) any {

nProp := strings.Split(key, ".")
nested := config

for i, prop := range nProp {

if i == len(nProp)-1 {

if v, ok := nested[prop]; ok {
return v
}

path := "'" + strings.Join(nProp[:i], ".") + "'"
if path == "''" {
path = "root object"
}

return getDefaultValueOrPanic(
key,
fmt.Sprintf("%s has no key '%s'", path, prop),
)
}

if _, ok := nested[prop].(map[string]any); !ok {
return getDefaultValueOrPanic(
key,
fmt.Sprintf("%s is not an object", strings.Join(nProp[:i+1], ".")),
)
}

nested = nested[prop].(map[string]any)
}

return nil
}

func getDefaultValueOrPanic(key, panicMsg string) any {
v, ok := defaults[key]
if !ok {
panic(panicMsg)
}
return v
}

func cast[T any](v any) T {
s, ok := v.(T)
if !ok {
panic(fmt.Sprintf("'%v' is not a %s", v, reflect.TypeOf(s)))
}
return s
}
Loading

0 comments on commit 6248807

Please sign in to comment.