標籤:
隨著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 學習筆記(一)