Go-Mega Tutorial 01 - Hello World
01-Hello World
一般計算機書的開頭都是 Hello World
我們亦不能免俗,所以本章我們的任務就是完成最簡單的 Hello World
本章的GitHub連結為: ofollow,noindex" target="_blank">Source ,Zip
建立目錄結構
與 Python 相比,Go 對程式碼存放的位置還是有講究的,畢竟這是由 Go 特殊的package引用機制
決定的,首先建立自己存放這次程式碼的資料夾
$ cd $GOPATH/src $ mkdir -p github.com/bonfy/go-mega-code $ cd github.com/bonfy/go-mega-code
這裡如果大家有Github賬號,而且想上傳到自己的repo的話,建議 github.com/your_user_name/repo_name 的資料夾
Hello World 應用
在 github.com/bonfy/go-mega-code 資料夾下 建立main.go
,這是我們程式的主入口
main.go
package main import "net/http" func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello World")) }) http.ListenAndServe(":8888", nil) }
短短不到10行程式碼,我們的 Hello World 應用就已經完成了,而且不需要任何的其他第三方Package,只需要引入官方的 net/http 就行了,就是這麼easy
讓我們來執行下面的命令,看下效果
$ go run main.go
現在開啟您的網路瀏覽器並在位址列中輸入以下URL:
http://localhost:8888 或者 http://127.0.0.1:8888
說明
這裡對上面的程式碼進行簡單的說明
這裡的func main()
是主程式入口,主要用到了
net/http
的兩個函式
func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) func ListenAndServe(addr string, handler Handler) error
HandleFunc
類似於 flask的app.route
,pattern
提供了路由路徑,handler是一個函式引數,這裡我們的程式中傳入的是一個匿名函式, 減少了程式碼
ListenAndServe
第一個引數為 addr,如果不提供ip,這裡只傳入埠,相當於0.0.0.0:8888
,第二個引數 Handler 傳入 nil,則表示使用 Default 的 Server
另外 輸出Hello World
的辦法,大致有三個,如下:
// Case 1: w.Write byte w.Write([]byte("Hello World")) // Case 2: fmt.Fprintf fmt.Fprintf(w, "Hello World") // Case 3: io.Write io.WriteString(w, "Hello World")
其中第一種用的是 ResponseWriter 的Write([]byte) (int, error)
方法, 而 後面兩種是稍微用到了 Go 裡面interface 的特性, ResponseWriter interface 要實現Write([]byte) (int, error)
的方法,所以也就實現了 io.Writer 方法,所以可以作為 io.Writer 的型別作為 後面兩個函式的引數。
這裡如果想更深入的瞭解 net/http 處理請求的話,可以看下Go原始碼中的net/http/server.go
或者看下Go的http包詳解