Basic auth in a seperate config file


I am new to go programming and would like to outsource the authentication against a RESTapi into a configfile.
Can anyone help me how best to implement something like this ? It is about basic auth in the first step. But the credentials should not be in the actual code.
I have already read something that this would be possible with a yaml or a json.

with kind regards


Well, you can just create a config file using JSON or YAML and then read its’ contents. Let’s assume you have something like this for the config file:

    "login": "user123",
    "password": "SuperSecure"

You can easily use encoding/json to read it. Let’s define an app config struct to hold your config like so:

// AppConfig stores our app's configuration.
type AppConfig struct {
	Login    string `json:"login"`
	Password string `json:"password"`

… and then read it using something along these lines:

// readConfigFile reads config file and will log.Fatal if there is a 
// problem opening the file (under the assumption that if we fail to
// initialize, the app literally can't run).
func readConfigFile(configPath string) AppConfig {
	var config AppConfig
	f, err := os.Open(configPath)
	if err != nil {
		// As an alternative here, you could return the error
		// and have the caller be responsible for dealing with it.
		log.Fatalf("Can't open config file %v.", configPath)
	defer f.Close()
	return config

… and to use it you can obviously do something like this:

myConfig := readConfigFile("myconfig.json")
// Do something with your configuration

There are ways to make this better, but this should get you well on your way.

Hello @Dean_Davidson,

Thank you for the good suggestions. I will start right away to deal with this project. :smiley:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.