Golang : File path independent of Operating System
There are times a program need to determine the operating system it is running on and construct a proper file path for file I/O.
Go has the http://golang.org/pkg/path/filepath/ package that will handle the cross plat form / operating system
Just use string(filepath.Separator)
through out your code will do.
Below is the an example code in Go:
package main
import (
"fmt"
"runtime"
"path/filepath"
)
func main() {
detect := "This OS is " + runtime.GOOS + " type and use "+ string(filepath.Separator) + " as file separator"
fmt.Println(detect)
}
The output will be
Unix/Linux
:
This OS is linux type and use / as file separator
Windows
:
This OS is windows type and use \ as file separator
See also : Golang : Detect (OS) Operating System
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+9.9k Golang : Intercept and process UNIX signals example
+15.9k Golang : Get future or past hours, minutes or seconds
+7.2k Golang : How To Use Panic and Recover
+6.2k Golang : Gorrila mux.Vars() function example
+7.7k nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
+7.7k Golang : Find network service name from given port and protocol
+24.5k Golang : How to write CSV data to file
+8k Golang : Inject/embed Javascript before sending out to browser example
+5.8k Golang : Get expvar(export variables) to work with multiplexer
+25.8k Golang : Convert CSV data to JSON format and save to file
+4.7k Golang : Grab news article text and use NLP to get each paragraph's sentences
+5.3k Golang : Extract sub-strings