多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] # 函数 ## 目录相关 ```go // 创建单级目录 func testMkdir() { if err := os.Mkdir("test", 0775); err != nil { panic(err) } } // 创建多级目录 func testMkdirAll() { if err := os.MkdirAll("test/a/b", 0775); err != nil { panic(err) } } // 创建临时目录 // centos默认10天后清理临时目录,配置/usr/lib/tmpfiles.d/tmp.conf func testMkdirTemp() { // 创建一个以 `test_` 开头的临时目录 if s, err := os.MkdirTemp("", "test_"); err != nil { panic(err) } else { fmt.Println(s) } } // 删除空文件夹 func testRemove() { if err := os.Remove("test/a/b"); err != nil { panic(err) } } // 递归删除文件夹 func testRemoveAll() { if err := os.RemoveAll("test"); err != nil { panic(err) } } // 查看临时目录 func testTempDir() { s := os.TempDir() fmt.Printf("temp dir: %v\n", s) } // 查看用户家目录 func testUserHomeDir() { if s, err := os.UserHomeDir(); err != nil { panic(err) } else { fmt.Printf("Home dir: %v\n", s) } } // 查看用户缓存目录 func testUserCacheDir() { if s, err := os.UserCacheDir(); err != nil { panic(err) } else { fmt.Printf("cache dir: %v\n", s) } } // 查看用户配置目录 func testUserConfigDir() { if s, err := os.UserConfigDir(); err != nil { panic(err) } else { fmt.Printf("config dir: %v\n", s) } } ``` ## 移动和修改名字 Rename 可以用作剪切(移动mv)功能、及重命名。适用于文件及目录 ```go func testRename() { if err := os.Rename("test.txt", "/tmp/test.txt"); err != nil { panic(err) } } ``` ## 工作目录 ```go // 查看当前工作目录 func testGetwd() { if dir, err := os.Getwd(); err != nil { panic(err) } else { fmt.Printf("dir is %v\n", dir) } } // 切换工作目录 func testChdir() { if err := os.Chdir("./11.socket"); err != nil { panic(err) } dir, _ := os.Getwd() fmt.Printf("dir is %v\n", dir) } ``` ## 修改权限 ```go func testChmod() { if err := os.Chmod("test", 0777); err != nil { panic(err) } } ``` ## 用户ID、租户ID ```go func testUserGroup() { // 当前用户id和租户id fmt.Printf("userID: %v, groupID: %v\n", os.Getgid(), os.Getuid()) // 调用者用户id和租户id fmt.Printf("caller userID: %v, groupID: %v\n", os.Geteuid(), os.Getegid()) } // Getgroups 返回调用者所属组的数字 ID 列表。 func testGetgroups() { s, err := os.Getgroups() if err != nil { panic(err) } fmt.Println(s) } ``` ## pid/ppid ```go func testPid() { fmt.Printf("pid: %v, ppid: %v\n", os.Getpid(), os.Getppid()) } ``` ## 软链接 ```go func testSymlink() { if err := os.Symlink("./test", "./test_link"); err != nil { panic(err) } } ``` ## 环境变量 这个做的环境只影响程序,不影响主机层面的配置 ```go // 获取环境变量 func testEnviron() { s := os.Environ() fmt.Printf("environ is: %v\n", s) } // 清理环境变量 func testClearenv() { os.Clearenv() } func testSetenv() { // 添加环境变量 if err := os.Setenv("name", "jiaxzeng"); err != nil { panic(err) } // 获取单个环境变量 s := os.Getenv("name") fmt.Printf("env is name: %v\n", s) // 删除环境变量 if err := os.Unsetenv("name"); err != nil { panic(err) } } ``` ## 退出程序 ```go func testExit() { os.Exit(1) } ``` ## 获取主机名 ```go func testHostname() { // 方法一 name, err := os.Hostname() if err != nil { panic(err) } fmt.Printf("hostname is: %v\n", name) // 方法二 name = os.Getenv("HOSTNAME") fmt.Printf("hostname is: %v\n", name) } ``` ## 判断错误类型 ```go func testError() { fmt.Println("-----------IsExist-----------------") err := os.Mkdir("test", 0775) if os.IsExist(err) { fmt.Println("dir is exists...") } fmt.Println("\n-----------IsNotExist-----------------") err = os.Chdir("/xxx") if os.IsNotExist(err) { fmt.Println("dir not exists...") } fmt.Println("\n-----------IsPermission-----------------") de, err := os.ReadDir("/opt/hislog/root") if os.IsPermission(err) { fmt.Println("Permission denied...") } for _, d := range de { fmt.Printf("Name: %s, isdir: %T\n", d.Name(), d.IsDir()) } fmt.Println("\n-----------IsTimeout-----------------") fmt.Println("\n-----------IsPathSeparator-----------------") n, _ := strconv.Atoi(fmt.Sprintf("%d", '/')) if os.IsPathSeparator(uint8(n)) { fmt.Println("path separator: /") } else { fmt.Println("path separator: \\") } } // 运行结果 // -----------IsExist----------------- // dir is exists... // -----------IsNotExist----------------- // dir not exists... // -----------IsPermission----------------- // Permission denied... // -----------IsTimeout----------------- // -----------IsPathSeparator----------------- // path separator: / ``` # File 结构体 ## 创建文件句柄 ```go func testFileCreate() { // 创建文件 // 文件存在且内容不为空,清空里面的内容 f, err := os.Create("test.txt") if err != nil { panic(err) } f.Close() // 创建临时文件 f2, err2 := os.CreateTemp("", "test_") if err2 != nil { panic(err2) } defer os.Remove(f2.Name()) f2.Close() // 打开文件 f3, err3 := os.Open("test.txt") if err3 != nil { panic(err3) } f3.Close() // 打开文件【推荐】 // 不存在创建,文件可读写,存在追加内容,设置文件的权限 f4, err4 := os.OpenFile("test.conf", os.O_CREATE|os.O_APPEND|os.O_RDWR, 0644) if err4 != nil { panic(err4) } f4.Close() } ``` ## 关闭文件句柄 通常使用延迟关闭文件的 ```go f, err := os.OpenFile("test.conf", os.O_CREATE|os.O_APPEND|os.O_RDWR, 0644) if err != nil { panic(err) } defer f.Close() ``` ## 读写文件 ```go // 读文件 func testFileRead() { f, err := os.OpenFile("test.txt", os.O_CREATE|os.O_APPEND|os.O_RDWR, 0644) if err != nil { panic(err) } defer f.Close() fmt.Println("filename", f.Name(), "context: ") buf := make([]byte, 5) for { n, err := f.Read(buf) if err == io.EOF { break } fmt.Print(string(buf[:n])) } } // 写文件 func testFileWrite() { f, err := os.OpenFile("test.txt", os.O_CREATE|os.O_APPEND|os.O_RDWR, 0644) if err != nil { panic(err) } defer f.Close() // 按照字节方式写入 _, err = f.Write([]byte("xiaodunan\n")) if err != nil { panic(err) } // 按照字符串方式写入 _, err = f.WriteString("jiaxzeng\n") if err != nil { panic(err) } } ``` # Process 结构体 ## kill ```go func testNewProcess() { p, err := os.FindProcess(os.Getpid()) if err != nil { panic(err) } fmt.Println("pid :", p.Pid) p.Kill() fmt.Println("11111") } // 运行结果 // pid : 127782 // signal: killed ``` # os/exec ## 只执行命令,不获取结果 ```go func testExecRun(command string) { err := exec.Command("/bin/sh", "-c", command).Run() if err != nil { panic(err) } } func main() { cmd := `ls` testExecRun(cmd) } ``` ## 执行命令,且获取结果 ```go func testExecOutput(cmd string) { out, err := exec.Command("/bin/sh", "-c", cmd).Output() if err != nil { panic(err) } if string(out) != "" { fmt.Println(string(out)) } } func main() { cmd1 := `ls` cmd2 := `systemctl stop firewalld` testExecOutput(cmd1) fmt.Println("----------------------------") testExecOutput(cmd2) } // 10.concurrency // 11.socket // 1.basicDataType // 2.operator // 3.flowControlStatement // 4.advancedDataType // 5.function // 6.builtInFunc // 7.fileOperations // 8.struct // 9.interface // ---------------------------- // panic: exit status 1 // goroutine 1 [running]: // main.testExecOutput({0x4b8ad9?, 0xc0000021a0?}) // /data/code/src/code.jiaxzeng.com/backend/study/6.builtInFunc/builtOS.go:276 +0xd9 // main.main() // /data/code/src/code.jiaxzeng.com/backend/study/6.builtInFunc/builtOS.go:347 +0x36 // exit status 2 ``` ## 执行命令,并区分stdout 和 stderr ```go func testExecRunOutErr(command string) { var stdout, stderr bytes.Buffer cmd := exec.Command("/bin/sh", "-c", command) cmd.Stdout = &stdout // 标准输出 cmd.Stderr = &stderr // 标准错误 cmd.Run() if stderr.String() != "" { fmt.Printf("command: %#v, Error: %v", command, stderr.String()) } else if stdout.String() != "" { fmt.Println(stdout.String()) } } func main() { cmd := `systemctl stop firewalld` testExecRunOutErr(cmd) } // command: "systemctl stop firewalld", Error: Failed to stop firewalld.service: Interactive authentication required. // See system logs and 'systemctl status firewalld.service' for details. ``` ## 执行管道符命令 ```go func testExecStdoutPipe() { c1 := exec.Command("ls") c2 := exec.Command("wc", "-l") c2.Stdin, _ = c1.StdoutPipe() c2.Stdout = os.Stdout c2.Start() c1.Run() c2.Wait() } func main() { testExecStdoutPipe() } // 11 ``` 官网文档:https://pkg.go.dev/os@go1.18.10