Skip to content
Multi platform library of configuration directories for Golang
Branch: master
Clone or download
shibukawa Merge pull request #3 from petemoore/relative-path-followup
Also support creating parent directories in WriteFile(...) method.
Latest commit e180dbd Mar 30, 2017


configdir for Golang

Multi platform library of configuration directory for Golang.

This library helps to get regular directories for configuration files or cache files that matches target operationg system's convention.

It assumes the following folders are standard paths of each environment:

  Windows: Linux/BSDs: MacOSX:
System level configuration folder %PROGRAMDATA% (C:\\ProgramData) ${XDG_CONFIG_DIRS} (/etc/xdg) /Library/Application Support
User level configuration folder %APPDATA% (C:\\Users\\<User>\\AppData\\Roaming) ${XDG_CONFIG_HOME} (${HOME}/.config) ${HOME}/Library/Application Support
User wide cache folder %LOCALAPPDATA% (C:\\Users\\<User>\\AppData\\Local) ${XDG_CACHE_HOME} (${HOME}/.cache) ${HOME}/Library/Caches


Getting Configuration

configdir.ConfigDir.QueryFolderContainsFile() searches files in the following order:

  • Local path (if you add the path via LocalPath parameter)
  • User level configuration folder(e.g. $HOME/.config/<vendor-name>/<application-name>/setting.json in Linux)
  • System level configuration folder(e.g. /etc/xdg/<vendor-name>/<application-name>/setting.json in Linux)

configdir.Config provides some convenient methods(ReadFile, WriteFile and so on).

var config Config

configDirs := configdir.New("vendor-name", "application-name")
// optional: local path has the highest priority
configDirs.LocalPath, _ = filepath.Abs(".")
folder := configDirs.QueryFolderContainsFile("setting.json")
if folder != nil {
    data, _ := folder.ReadFile("setting.json")
    json.Unmarshal(data, &config)
} else {
    config = DefaultConfig

Write Configuration

When storing configuration, get configuration folder by using configdir.ConfigDir.QueryFolders() method.

configDirs := configdir.New("vendor-name", "application-name")

var config Config
data, _ := json.Marshal(&config)

// Stores to local folder
folders := configDirs.QueryFolders(configdir.Local)
folders[0].WriteFile("setting.json", data)

// Stores to user folder
folders = configDirs.QueryFolders(configdir.Global)
folders[0].WriteFile("setting.json", data)

// Stores to system folder
folders = configDirs.QueryFolders(configdir.System)
folders[0].WriteFile("setting.json", data)

Getting Cache Folder

It is similar to the above example, but returns cache folder.

configDirs := configdir.New("vendor-name", "application-name")
cache := configDirs.QueryCacheFolder()

resp, err := http.Get("")
if err != nil {
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)

cache.WriteFile("", body)




You can’t perform that action at this time.