Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Best practice struct configuration pattern for Golang #21

Open
japananh opened this issue Oct 16, 2023 · 0 comments
Open

Best practice struct configuration pattern for Golang #21

japananh opened this issue Oct 16, 2023 · 0 comments
Assignees
Labels

Comments

@japananh
Copy link
Owner

japananh commented Oct 16, 2023

Best practice struct configuration pattern for Golang

Before

package main

type Server struct {
    maxConn int
    id              string
    tls             bool
}

// Problem: Parameter will grow when we need more configs
func newServer(maxConn int, id string, tls bool) *Server {
    return &Server{
        maxConn: maxConn,
        id:              id,
        tls:             tls,
}

func main() {
    s := NewServer(20, "id", false)
    
    fmt.Printf("%+v\n", s)
}

After

package main

type OptFunc func(*Opts)

type Opts struct {
    maxConn int
    id              string
    tls             bool
}

func defaultOpts() Opts {
    return Opts{
        maxConn: 10, 
        id:              "default",
        tls:             false,
    }
}

func withTLS(opts *Opts) {
    opts.tls = true
}

func withMaxConn(n int) OptFun {
    return func(opts *Opts) {
        opts.maxConn = n
    }
}

type Server struct {
    Opts
}

func NewServer(opts ...OptFunc) *Server {
    o := defailtOpts()

    for _, fn := range opts {
        fn(&o)
    }

    return &Server{
        Opts: o,
    }
}

func main() {
    s := NewServer(withTLS, withMaxConn(20))
    
    fmt.Printf("%+v\n", s)
}
@japananh japananh self-assigned this Oct 16, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant