This is a creation in Article, where the information may have evolved or changed.
Get command-line arguments
先定义变量var value = flag.String("key", "默认值", "说明:xxx")再解析命令flag.Parse()
Get information about the current stack frame
runtime包的Caller方法可以获得栈帧的信息,skip为栈帧的位置,0为当前函数的位置。其中pc为program counter(我也不理解这个含义),file为当前函数所在的文件的文件名,lile为代码行号,ok为是否可以获取到信息func Caller(skip int) (pc uintptr, file string, line int, ok bool)例如:有个函数ABC(),在包pack下,然后在main方法里调用了pack.ABC()在ABC里面调用_,filename,_c_ := runtime.Caller(0)可以获得ABC函数所在的文件的文件名包括路径。_,filename,_c_ := runtime.Caller(1)可以获得main函数的文件名包括路径,因为是main调用了ABC,main比ABC先1步进栈
Build a file server
首先获得文件服务器的handlerh := http.FileServer("文件服务根路径");添加url和handler映射http.Handle("/", h)开启服务http.ListenAndServe(":" + port, nil);
Create a pair of files (read and write connections)
想文件w写入数据,可以从r读取出来r, w, _ := os.Pipe();下面是将os.Stdout作为w来写入,然后可以从r里读取出写入的内容r, w, _ := os.Pipe();originalOut := os.Stdoutos.Stdout = woutChan := make(chan string)go func() {var buf bytes.Bufferio.Copy(&buf, r)outChan <- buf.String()}()time.Sleep(1 * time.Second)fmt.Print("aaa")w.Close()os.Stdout = originalOutinfo := <-outChanfmt.Println(info)
Run-time Execution cmd
exec包的Command函数可以执行cmdfunc Command(name string, arg ...string) *Cmd比如:执行go main.gocmdName := "go"cmdArgs := []string{"run", "main.go"}cmd := exec.Command(cmdName, cmdArgs...)