目录
下载安装
1. 下载安装包:All releases - The Go Programming Language
2. 解压安装包
3. 配置 ~/.bash_profile
$ pwd
/home/users/tianrenbao/go17
$
$ ls
go go1.17.13.linux-amd64.tar.gz
$
$ tail -n6 ~/.bash_profile
export GOROOT=/home/users/tianrenbao/go17/go/
#export GOROOT=/home/users/tianrenbao/go16/go/
#export GOROOT=/home/users/tianrenbao/go14
#export GOROOT=/home/users/tianrenbao/go
export PATH=$GOROOT/bin:$PATH
注意:循环里创建的变量在该块作用域内,是共享同一个存储位置
错误示例:
可以看到输出的结果中,num值都为3。
修正:
注意这里的第9行,再引入了一个变量。
使用defer在函数的入口、出口处执行所需逻辑
基本函数
读写文件
os.ReadFile(fileName)
package main
import (
"fmt"
"os"
"strings"
)
func main() {
fileContent, err := os.ReadFile("/proc/sys/kernel/sched_bt_on")
if err != nil && strings.TrimSpace(string(fileContent)) == "1" {
fmt.Println("bt is enabled.")
}
}
ioutil.ReadFile(fileName)
func GetMachineMemoryCapacity() (uint64, error) {
out, err := ioutil.ReadFile("/proc/meminfo")
if err != nil {
return 0, err
}
}
bufio.NewScanner(fileFD)
func getCgroupDestination(subsystem string) (string, error) {
f, err := os.Open("/proc/self/mountinfo")
if err != nil {
return "", err
}
defer f.Close()
s := bufio.NewScanner(f)
buf := make([]byte, 0, bufio.MaxScanTokenSize*10)
s.Buffer(buf, cap(buf))
for s.Scan() {
if len(s.Text()) > bufio.MaxScanTokenSize {
fmt.Println(bufio.ErrTooLong, len(s.Text())/1024, "KB")
continue
}
fields := strings.Split(s.Text(), " ")
if len(fields) < 10 {
// broken mountinfo?
continue
}
if fields[len(fields)-3] != "cgroup" {
continue
}
for _, opt := range strings.Split(fields[len(fields)-1], ",") {
if opt == subsystem {
return fields[3], nil
}
}
}
if err := s.Err(); err != nil {
fmt.Println(err)
return "", err
}
return "", ErrNoCgroupMountDestination
}
json.NewDecoder(fileFD).Decode(structVar)
// getContainerMeta get one matrix container's meta, /matrix/run/container/{cid}
func getContainerMeta(filePath string) (*matrixContainerMeta, error) {
file, err := os.Open(filePath)
if err != nil {
klog.Infof("fail open container meta file %s, %v", filePath, err)
return nil, err
}
defer file.Close()
meta := &matrixContainerMeta{}
if err = json.NewDecoder(file).Decode(meta); err != nil {
klog.Infof("%s fail decode container meta json to struct, %v", filePath, err)
return nil, err
}
}
时间
package main
import (
"fmt"
"time"
)
func main(){
ts := time.Now().Unix() // second
fmt.Println(ts)
}
select case&wait.Until
select case
// CleanUp tcp_throt tos_cgroup
func CleanUp(stop <-chan struct{}) {
immediately := time.NewTimer(1 * time.Second)
defer immediately.Stop()
ticker := time.NewTicker(1 * time.Minute)
defer ticker.Stop()
for {
select {
case <-immediately.C:
case <-ticker.C:
case <-stop:
klog.Infof("stop cleanup")
return
}
m.cleanup()
}
}
wait.Until
go wait.Until(Cleanup, time.Duration(controller.syncIntervalSec)*time.Second, stopCh)
ctx := context.TODO()
ctx.Done()