object

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: May 16, 2024 License: MIT Imports: 5 Imported by: 0

README

object

object is a small library which allows you to create new struct instance or set instance value with default、yaml、json tag

go get github.com/go-pkg-utils/object

For example:

default tag:

func main() {
    db := object.NewWithDefault[DB]()

    data, _ := json.Marshal(db)

    fmt.Println(string(data))
}

type DB struct {
    Redis struct {
        Host string `default:"127.0.0.1"`
    }
}

// output:  {"Redis":{"Host":"127.0.0.1"}}

yaml tag:

db.yaml

redis:
    Host: 127.0.0.1
func main() {
    v := viper.New()
    v.SetConfigFile("db.yaml")
    v.ReadInConfig()

    db := object.NewWithYaml[DB](v)

    data, _ := json.Marshal(db)

    fmt.Println(string(data))
}

type DB struct {
    Redis struct {
        Host string `yaml:"redis.Host"`
    }
}

// type DB struct {
//     Redis struct {
//         Host string `yaml:"Host"`
//     } `yaml:"redis"`
// }

// output:  {"Redis":{"Host":"127.0.0.1"}}

json tag:

func main() {
    str := `{
        "redis": {
            "Host": "127.0.0.1"
        }
    }`

    db := object.NewWithJson[DB](str)

    data, _ := json.Marshal(db)

    fmt.Println(string(data))
}

type DB struct {
    Redis struct {
        Host string `json:"redis.Host"`
    }
}
 
// type DB struct {
//     Redis struct {
//         Host string `json:"Host"`
//     } `json:"redis"`
// }

// output:  {"Redis":{"Host":"127.0.0.1"}}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewWithDefault

func NewWithDefault[T Struct]() *T

func NewWithJson

func NewWithJson[T Struct](json string) *T

func NewWithYaml

func NewWithYaml[T Struct](yaml *viper.Viper) *T

func SetDefault added in v1.0.2

func SetDefault[T Struct](obj *T) *T

func SetJson added in v1.0.2

func SetJson[T Struct](obj *T, json string) *T

func SetYaml added in v1.0.2

func SetYaml[T Struct](obj *T, yaml *viper.Viper) *T

Types

type Struct added in v1.0.1

type Struct = interface{}

Jump to

Keyboard shortcuts

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