Go 學習筆記(一)

來源:互聯網
上載者:User

標籤:

隨著Go的應用越來越火熱,自己也終於開始學習了。平時經常用C,看著Go還是比較親切的。好了,開始。

 

今天主要是按照樹上的內容自己簡單的實踐了下最基本的輸出,以及網頁功能,上代碼:

1 package main2 3 import (4     "fmt"5 )6 7 func main() {8     fmt.Printf("Hello world\n")9 }

加法運算代碼:

 1 package main 2  3 import ( 4     "fmt" 5 ) 6  7 func add(a int,b int)(c int){ 8     c= a+b 9     return c10 }11 12 13 func main() {14     c:=add(1,2)15     fmt.Println(c)16 }

網頁“Hello world”代碼:

 1 package main 2  3 import ( 4     "fmt" 5     "net/http" 6 ) 7 func sayHelloName(w http.ResponseWriter,r *http.Request){ 8     fmt.Fprintf(w,"hello,world") 9 10 }11 12 func main() {13 14     http.HandleFunc("/",sayHelloName)15 }

登入:

 

網頁登入代碼:

 1 package main 2  3 import ( 4     "fmt" 5     "html/template" 6     "net/http" 7     "log" 8 ) 9 10 func login(w http.ResponseWriter,r* http.Request){11 12     fmt.Println("method:", r.Method)13     if r.Method == "GET"{14         t,_:=template.ParseFiles("/Users/mac/IdeaProjects/go1/login.gtpl")15         t.Execute(w,nil)16     }else{17         r.ParseForm()18         fmt.Println("username:",r.Form["username"])19         fmt.Println("password",r.Form["password"])20     }21 }22 23 func main() {24     http.HandleFunc("/login",login)25     err:=http.ListenAndServe(":9090",nil)26     if err != nil {27         log.Fatal("ListenAndServe: ", err)28     }29 }

運行結果:

consle:

 

這裡需要注意的是,程式在Mac環境下,網頁模板路徑需要使用絕對路徑“/Users/mac/IdeaProjects/go1/login.gtpl” ,不然會報如下錯誤:

runtime error: invalid memory address or nil pointer dereference goroutine 5 

 

 

 

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.