How to use .toml file to parse IP address and port to http server

306 views
Skip to first unread message

afriyie...@gmail.com

unread,
Sep 29, 2019, 6:59:29 AM9/29/19
to golang-nuts
Hi,

How I can use the .toml file to parse IP address and port to simple http server instead of using flags
I have a config.toml file which contains these parameters in

PORT = "8000"
Address = "localhost"


//Parameters type struct as
type Config struct {
PORT    string
Address string
}

I can load file in main function as

var conf Config
if _, err := toml.Decode("config.toml", &conf); err != nil {
// handle error
}


//simple http server main function

func main() {
var dir string

flag.StringVar(&dir, "dir", ".", "the directory to serve files from. Defaults to the current dir")
flag.Parse()
r := mux.NewRouter()

// This will serve files under http://localhost:8000/static/<filename>
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir))))

srv := &http.Server{
Handler:      r,
Addr:         "127.0.0.1:8000",
WriteTimeout: 15 * time.Second,
ReadTimeout:  15 * time.Second,
}

log.Fatal(srv.ListenAndServe())
}

Any help?

Andrew Pillar

unread,
Sep 29, 2019, 10:18:55 AM9/29/19
to afriyie...@gmail.com, golang-nuts
Use net.JoinHostPort to concatenate the values you have in the struct
and pass the to http.Server struct.

if _, err := toml.Decode("config.toml", &conf); err != nil {
// handle error
}

addr, err := net.JoinHostPort(conf.Address, conf.PORT)

if err != nil {
// handle error
}

src := &http.Server{
Addr: addr,
}

Be sure to set explicit struct tags on your destination struct that
will be used for unmarshalling the toml. This way the decoder will know
which struct fields to populate.

type Config struct {
PORT string `toml:"port"`
Address string `toml:"address"`
}

This will only be necessary though if you want the fields to map
differently depending on their name.

afriyie...@gmail.com

unread,
Sep 30, 2019, 4:06:20 AM9/30/19
to golang-nuts
Hi,

I have applied similar scenario to the function below but am not getting the Ip address and the port number. Below is the function

var addr string

func init(){

var conf Config

if _, err := toml.Decode("config.toml", &conf); err != nil {
        // handle error
    }
    addr = net.JoinHostPort(conf.Addr, conf.Port)
    fmt.Println(addr)  // This printing empty
 
}


func main() {
   
    server := NewServer()

    go func() {

        if err := server.ListenAndServeTLS("/home/cumucore/diam/server.crt", "/home/cumucore/diam/server.key"); err != nil && err != http.ErrServerClosed {
            logger.Fatalf("Could not listen on %s: %v\n", addr, err)

            if err := server.ListenAndServe(); err != nil {
                logger.Fatalf("Could not listen on %s: %v\n", addr, err)
            }

        }
    }()
}


// Create a new server
func NewServer() *http.Server {

    return &http.Server{
        Addr:         addr,
        Handler:      diam.NewRouter(),
        ErrorLog:     logger,
        ReadTimeout:  5 * time.Second,
        WriteTimeout: 10 * time.Second,
        IdleTimeout:  15 * time.Second,
    }
}

Ther config.toml file contain the key values as
Addr = "192.168.9.186"
Port = "8000"

What might be the problem in this case

afriyie...@gmail.com

unread,
Sep 30, 2019, 4:47:11 AM9/30/19
to golang-nuts
Hi,

I have solve the problem and it works now. Thanks.
Reply all
Reply to author
Forward
0 new messages