跳轉到內容

Go 程式設計/簡單 Web 應用

來自華夏公益教科書,開放的書籍,為開放的世界

標準庫中有多個包。其中一個包叫做 net/http。該包可用於建立簡單的 Web 應用程式。以下是一個簡單的例子,當訪問 localhost:8080 時會輸出 Hello world!。

package main

import (
   "fmt"
   "log"
   "net/http"
)

func helloFunc(w http.ResponseWriter, r *http.Request) {
   fmt.Fprintf(w, "Hello world!")
}

func main() {
	http.HandleFunc("/", helloFunc)
	http.ListenAndServe(":8080", nil)
}

您可能會看到出現了一些新的東西。

import (
   "fmt"
   "net/http"
)

如您所見,fmt 包再次被匯入。但是,net/http 包也被匯入。

func helloFunc(w http.ResponseWriter, r *http.Request)

聲明瞭一個名為 helloFunc 的函式。該函式使用 http.ResponseWriter 型別來構造 HTTP 響應。*http.Request 是指向伺服器接收的或客戶端傳送的 HTTP 請求的指標。

fmt.Fprintf(w, "Hello world!")

在這行中,字串 "Hello world!" 被寫入 ResponseWriter,以便在輸出中顯示。

func main() {
	http.HandleFunc("/", helloFunc)
	http.ListenAndServe(":8080", nil)
}

main 函式已宣告,包含兩個操作。處理程式函式 helloFunc 已連線到 "/" 路由。最後,ListenAndServe 已呼叫,埠為 "8080",第二個引數未指定路由器。

現在,當程式執行時,預計將在網站 localhost:8080 上顯示 Hello world!

華夏公益教科書