Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to choose func at runtime for different operating systems

Tags:

go

I really like the cross-compile/platform ease for many tasks that I can get with GO. I have a question regarding, I guess, the equivalent of a #ifdef / #else type of construct for executing/compiling a function based upon the operating system.

Here's the scenario - let's say I have a function that inserts information into the OS's control structures to launch a process at the next time the user starts up their system. On Windows I would update the 'RUN/RUNONCE' registry entry for the user, on MAC there would be a plist entry, etc.

In essence, I'd like to be able to write someone analogous to this (or have overloaded OS specific functions):

func setStartupProcessLaunch () {
    if [OS is Windows] {
        updateRegistry(){}
    } else if [OS is Darwin] {
        updatePlist(){}
    } else if [OS is Linux] {
        doLinuxthing() {}
    }
}

Given the static compilation, any of the routines that aren't called would be flagged as a compilation error. So ideally, I'd like to surround my 'doSpecificOS()' functions in #ifdef WINDOWS, #ifdef MAC type of blocks -- what's the proper way to accomplish this? My hope is that I don't need to create several project trees of the same program for each OS platform.

like image 945
user2644113 Avatar asked Dec 06 '13 13:12

user2644113


1 Answers

You could create files with following pattern: <pkgname>_<osname>.go

For example:

  • your_package_linux.go
  • your_package_darwin.go
  • your_package_windows.go

Each file could contain function definition for concrete os, in your case it is func setStartupProcessLaunch().

You could see how it is implemented in standard os/signal package for example.

like image 81
maxbublis Avatar answered Nov 16 '22 01:11

maxbublis