Go語言開發,step by step (Part 1:從hello world到網站開發)

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

 

通過上一篇轉載的文章 "Yesterday Once More ---再次遇到Go語言",可以搭建Go語言開發環境了。

現在開始Go語言(Golang)程式開發, here we Go.

 

Example 1. 最簡單的程式Let's Go:

package main // There must be a so-called main package for a Go EXE.import  "fmt" // fmt is a package including Printfunc main(){ //The entry of a Go EXE fmt.Print("Hello,Let's Go") //Main program context}


 

程式碼非常簡單,任何有編程功底的人都可以看懂。

在Eclipse中Run即可在Console中看到列印結果:

Hello,Let's Go


 

Example 2. 並行程式(多協程,可以簡單地理解成多線程程式)

 (*注1,協程者,輕量級線程也,因其輕量級,系統中的協程可以百萬計)。具體實現此處不細表。

*注2,紫色顏色處代碼錶示本例子是改自上面的例子,同時紫色本身代碼錶示修改/添加的代碼。這樣更方便讀者閱讀。)

 這基本上是一個Go語言中並發程式的雛形;但是大家其實可能已經看出,主進程在建立協程後即退出,因此可能該協程根本沒有機會執行。

 

package main // There must be a so-called main package for a Go EXE.import  "fmt" // fmt is a package including Printfunc Coroutine(){ //Coroutine functionfmt.Println("go")}func main(){ //The entry of a Go EXE//Main program contextfmt.Println("Hello,Let's ..."); go Coroutine();}



 

Example 3. 引入同步機制,實現真正的並行程式

Golang中用channel實現協程間通訊, 可以用sync包中的Mutex, RWMutex來實現協程間同步以及資源共用,channel也可以用來協程間同步。

Golang中的channel就類似於linux中的管道,原理一樣。

 

 

package main // There must be a so-called main package for a Go EXE.import  "fmt" // fmt is a package including Printfunc Coroutine(ch chan int, i int ){ //Coroutine functionfmt.Println("go", i);ch <- i; //write a int value to chan}func main(){ //The entry of a Go EXE//Main program contextfmt.Println("Hello,Let's ..."); chs := make([]chan int, 10); //make an array containning 10 chanfor i := 0; i < 10; i++{ // chs[i] = make(chan int); //create a chan valuego Coroutine(chs[i], i); //run a coroutine}//For the main process, read value from the chan arrayfor _,ch := range(chs){ //loop the array//read value from each chan if there's a value; //otherwise, it is locked.c := <- ch; fmt.Println("Main Process gets from Coroutine:", c)}} 


 

(*Go程式每句結束不必用分號;但是我個人習慣還是加了個分號。)
此程式建立了10個協程,主程式與協程之間通訊以及同步。

輸出:

Hello,Let's ...go 0go 1go 2go 3go 4go 5go 6go 7go 8go 9Main Process gets from Coroutine: 0Main Process gets from Coroutine: 1Main Process gets from Coroutine: 2Main Process gets from Coroutine: 3Main Process gets from Coroutine: 4Main Process gets from Coroutine: 5Main Process gets from Coroutine: 6Main Process gets from Coroutine: 7Main Process gets from Coroutine: 8Main Process gets from Coroutine: 9


Example 4. 加點進階技巧:使用匿名函數+多核支援

(*注,匿名函數與是否多核完全沒有聯絡,只是為了在一個例子同時用這個2個技巧)

 

package main // There must be a so-called main package for a Go EXE.import "fmt" // fmt is a package including Printimport "runtime"func main(){ //The entry of a Go EXE//Main program contextfmt.Println("Hello,Let's ..."); chs := make([]chan int, 10); //make an array containning 10 chanruntime.GOMAXPROCS(10);//Make the coroutines running in 10 CPUsfor i := 0; i < 10; i++{ // chs[i] = make(chan int); //create a chan valuego func(ch chan int, i int){//Use anonymous function insteadfmt.Println("go", i);ch <- i; //write a int value to chan}(chs[i],i); //pass the value into funciton}//For the main process, read value from the chan arrayfor _,ch := range(chs){ //loop the array//read value from each chan if there's a value; //otherwise, it is locked.c := <- ch; fmt.Println("Main Process gets from Coroutine:", c)}} 


 

 

這樣,我們就實現了一個完整的在多核系統上啟動並執行並行程式。
此例在我的系統上(Intel Core 2 Duo) 的輸出結果是:

Hello,Let's ...go 0go 4go 5go 6go 7Main Process gets from Coroutine: 0go 2go 8go 9go 1Main Process gets from Coroutine: 1Main Process gets from Coroutine: 2go 3Main Process gets from Coroutine: 3Main Process gets from Coroutine: 4Main Process gets from Coroutine: 5Main Process gets from Coroutine: 6Main Process gets from Coroutine: 7Main Process gets from Coroutine: 8Main Process gets from Coroutine: 9


Example 5. 做一個最簡單的網站, Let's Go!

 Webserver監聽8080連接埠,收到用戶端的yes的時候,做出回答。

 

package main // There must be a so-called main package for a Go EXE.import("fmt";"io";"log";"net/http")func mainHandler(w http.ResponseWriter, r *http.Request){io.WriteString(w,"Let's Go");}func main(){http.HandleFunc("/yes", mainHandler);fmt.Print("Sever is ready, shall we go?");err := http.ListenAndServe(":8080",nil);if err != nil{log.Fatal("ListenAndServe:",err.Error());}} 


 

程式可以在Eclipse中執行,也可以在命令列中執行,如。

用戶端是用IE瀏覽器訪問http://localhost:8080,並寫訊息"yes"到8080連接埠。

(*注,我遇到問題是我的殺毒軟體一直阻擋我的main程式,這種情況下,需要暫時關閉該保護)

 

 

第一部分就到此為止;用意是用鮮明的例子激起大家(包括我自己)對這門語言的好奇或者喜愛。

 

參考文獻

1. golang.org

2. 《Go語言編程》徐世偉 呂桂華等編著,人民郵電出版社

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.