Skip to content

Instantly share code, notes, and snippets.

@atulsingh0
Last active September 28, 2022 03:23
Show Gist options
  • Save atulsingh0/147dff3d16850600098bb7d552b10598 to your computer and use it in GitHub Desktop.
Save atulsingh0/147dff3d16850600098bb7d552b10598 to your computer and use it in GitHub Desktop.
Package OS - Golang
// Go Playground
// https://go.dev/play/p/MF-dT57HXTM
package main
import (
"fmt"
"os"
)
func main() {
// creating dir /tmp/gopal
if err := os.Mkdir("/tmp/gopal", 0750); err == nil {
fmt.Println("Dir has been created.")
} else {
fmt.Println(err)
}
// create the dir with parent dir
if err := os.MkdirAll("/tmp/go1/go2/go3", 0750); err == nil {
fmt.Println("Dir has been created.")
} else {
fmt.Println(err)
}
}
// Go Playground
// https://go.dev/play/p/9wqZwtlDdQk
package main
import (
"fmt"
"os"
)
func main() {
// fetch Language env var
// If env exists, return value else return empty
fmt.Println("PAGER env:", os.Getenv("PAGER"))
// to check if Env exists or not
// if env var does not exists, retrun false else true
if val, ok := os.LookupEnv("PAGER"); ok == false {
fmt.Println("Env var does not exists.")
} else {
fmt.Println("Env val exists and value is:", val)
}
}
// Go Playground
// https://go.dev/play/p/Knvmf4bq5w0
package main
import (
"fmt"
"os"
)
func main() {
fh, err := os.Stat("/etc/hosts")
// Error check
if err != nil {
fmt.Println(err.Error())
}
// Fetching Stats
fmt.Println("File Name:", fh.Name())
fmt.Println("File Size (byte):", fh.Size())
fmt.Println("File Permissions:", fh.Mode())
fmt.Printf("File Permissions (octal): %#o\n", fh.Mode().Perm())
fmt.Println("File, Is it a direcotory?:", fh.IsDir())
fmt.Println("File, Is it a regular file?:", fh.Mode().IsRegular())
fmt.Println("File last modification time:", fh.ModTime())
}
// Go Playground
// https://go.dev/play/p/rVolsli4vW8
package main
import (
"fmt"
"os"
"strings"
)
func main() {
// fetch all the env variable
env := os.Environ()
// loop over env var
for _, v := range env {
// split the key and value
data := strings.Split(v, "=")
fmt.Println(data[0], "--->", data[1])
}
}
// Go Playground
// https://go.dev/play/p/Q1aQHlJwwph
package main
import (
"fmt"
"os"
)
func main() {
file, err := os.ReadFile("/etc/hosts")
if err != nil {
fmt.Println(err)
} else {
fmt.Println(string(file))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment