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
+6.1k Golang : Measure execution time for a function
+9k Golang : Go as a script or running go with shebang/hashbang style
+7.1k Golang : Squaring elements in array
+17.1k Golang : XML to JSON example
+30.4k Golang : How to verify uploaded file is image or allowed file types
+14.9k Golang : Basic authentication with .htpasswd file
+12.6k Golang : Exit, terminating or aborting a program
+8.7k Golang : Combine slices but preserve order example
+16.5k Golang : Check if a string contains multiple sub-strings in []string?
+12k Golang : Setup API server or gateway with Caddy and http.ListenAndServe() function example
+16.6k Golang : Merge video(OpenCV) and audio(PortAudio) into a mp4 file
+10.5k Generate Random number with math/rand in Go