1. 程式人生 > >我的第一個Go web程序 紀念一下

我的第一個Go web程序 紀念一下

brush 選擇 pan fmt resp main nbsp gpo pac

參考Go web編程,很簡單的程序:

  大致的步驟:

    1. 綁定ip和端口
    2. 綁定對應的處理器或者處理器函數,有下面兩種選擇,選擇一種即可監聽ip及端口
      1. 處理器:
        1. 定義一個struct結構體
        2. 然後讓這個結構體實現ServeHTTP的接口
        3. 創建一個該結構的實例
        4. 將該實例的地址(指針)作為參數傳遞給Handle
      2. 處理器函數
        1. 定義一個函數
        2. 該函數必須和ServeHTTP一樣的函數簽名
        3. 函數名直接作為參數傳遞給HandleFunc
    3. 訪問綁定的ip加port

使用處理器形式:

package main
import (
	"fmt"
	"net/http"
)
type Home struct{}
type About struct{}
func (h *Home) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "this is home")
}
func (a *About) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "this is about")
}
func main() {
	server := http.Server{
		Addr: "127.0.0.1:8080",
	}
	home := &Home{}
	about := &About{}
	http.Handle("/home", home)
	http.Handle("/about", about)
	server.ListenAndServe()
}

  

使用處理器函數形式:

package main
import (
	"fmt"
	"net/http"
)
func home(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "this is home2")
}
func about(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "this is about2")
}
func main() {
	server := http.Server{
		Addr: "127.0.0.1:8080",
	}
	http.HandleFunc("/home", home)
	http.HandleFunc("/about", about)
	server.ListenAndServe()
}

  

我的第一個Go web程序 紀念一下