原 golang小技巧匯總

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

擷取命令列的參數

先定義變數var value = flag.String("key", "預設值", "說明:xxx")再解析命令flag.Parse()

獲得當前棧幀的資訊

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步進棧

搭建一個檔案伺服器

首先獲得檔案伺服器的handlerh := http.FileServer("檔案服務根路徑");添加url和handler映射http.Handle("/", h)開啟服務http.ListenAndServe(":" + port, nil);

建立一對(讀寫串連)的檔案

想檔案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)

運行時執行cmd

exec包的Command函數可以執行cmdfunc Command(name string, arg ...string) *Cmd比如:執行go main.gocmdName := "go"cmdArgs := []string{"run", "main.go"}cmd := exec.Command(cmdName, cmdArgs...)

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.