Configuration Files in Golang

While learning the Go language and writing a few utilities, I played around with with various methods of setting up a proper configuration scheme.  Being a Perl hacker and a PHP… uh, programmer, I naturally started with string maps.  Ah, the associative array, my old friend.  But since Go is a statically typed language, a string map isn’t the best way to save configuration variables.  Using a struct is a far better method for saving configuration variables because all of your values are already of the correct type.  Also, the JSON package does a very nice job of outputting structs into pretty, human-readable JSON strings.

So I wrote this little wrapper to make the task of reading and writing configuration files a bit easier.  It only contains two functions:  Read and Write.  All that is required is to supply a filename and a pointer to your struct.


package main
import ""
const config_file = "myconfig.conf"

func main () {
  config := struct {
    Name string
    Addr string
    Port int
    "Server McServerface",

  err := conf.Write(config_file, &config)
  if err != nil {

View Source

Leave a Reply

Your email address will not be published. Required fields are marked *