mbridges
mbridges

Reputation: 184

How to write a Go function to accept different structs?

I am writing a function that parses a config JSON file and using json.Unmarshal stores its data in a struct. I've done some research and it's gotten me the point where I have a Config struct and a Server_Config struct as a field in config to allow me to add more fields as I want different config-like structs.

How can I write one parseJSON function to work for different types of structs?

Code:

Server.go

type Server_Config struct {
    html_templates string
}

type Config struct {
    Server_Config
}

func main() {
    config := Config{}
    ParseJSON("server_config.json", &config)
    fmt.Printf("%T\n", config.html_templates)
    fmt.Printf(config.html_templates)
}

config.go

package main
import(
    "encoding/json"
    "io/ioutil"
    "log"
)

func ParseJSON(file string, config Config) {
    configFile, err := ioutil.ReadFile(file)
    if err != nil {
        log.Fatal(err)
    }
    err = json.Unmarshal(configFile, &config)
    if err != nil {
        log.Fatal(err)
    }
}

Or if there is a better way to do all this let me know that as well. Pretty new to Go and I have Java conventions carved into my brain.

Upvotes: 4

Views: 835

Answers (1)

OneOfOne
OneOfOne

Reputation: 99274

Use interface{}:

func ParseJSON(file string, val interface{}) {
    configFile, err := ioutil.ReadFile(file)
    if err != nil {
        log.Fatal(err)
    }
    err = json.Unmarshal(configFile, val)
    if err != nil {
        log.Fatal(err)
    }
}

Calling the function is the same.

Upvotes: 6

Related Questions