Here are some examples of Go code that support both Windows and Linux:
Example 1: Using `os` Package to Determine Operating System
go
package main
import (
"fmt"
"os"
)
func main() {
if os.Getenv("GOOS") == "windows" {
fmt.Println("Running on Windows")
} else {
fmt.Println("Running on Linux")
}
}
Example 2: Using `filepath` Package to Join Paths
go
package main
import (
"fmt"
"path/filepath"
)
func main() {
path := filepath.Join("path", "to", "file.txt")
fmt.Println(path)
}
Example 3: Using `os/exec` Package to Run Commands
go
package main
import (
"fmt"
"os/exec"
)
func main() {
if os.Getenv("GOOS") == "windows" {
cmd := exec.Command("cmd", "/c", "dir")
} else {
cmd := exec.Command("ls", "-l")
}
out, err := cmd.CombinedOutput()
if err != nil {
fmt.Println(err)
} else {
fmt.Println(string(out))
}
}
Example 4: Using `os/user` Package to Get User Information
go
package main
import (
"fmt"
"os/user"
)
func main() {
u, err := user.Current()
if err != nil {
fmt.Println(err)
} else {
fmt.Println(u.Username)
}
}
Example 5: Using `os/exec` Package to Run System Commands
go
package main
import (
"fmt"
"os/exec"
)
func main() {
if os.Getenv("GOOS") == "windows" {
cmd := exec.Command("systeminfo")
} else {
cmd := exec.Command("uname", "-a")
}
out, err := cmd.CombinedOutput()
if err != nil {
fmt.Println(err)
} else {
fmt.Println(string(out))
}
}
These examples demonstrate how to use Go's standard library packages to support both Windows and Linux operating systems.
Citations:[1] https://tip.golang.org/wiki/WindowsCrossCompiling
[2] https://go.dev/doc/tutorial/getting-started
[3] https://www.zombiezen.com/blog/2020/09/how-i-packaged-go-program-windows-linux/
[4] https://betterprogramming.pub/deploying-to-multiple-oss-with-go-d87fc1681720?gi=70d06eb6ec4a
[5] https://trio.dev/what-is-golang-used-for/