[實作] 從零開始用 Golang 寫網頁 : 05 設置 route 與 server
在這裡我們新增 route 與 server 物件,另外之前是用預設的 route 物件,這次試著使用第三方的
1 2 3 4 5 6 7
   | import ( 	"fmt" 	"net/http" 	"text/template"
  	"github.com/julienschmidt/httprouter" )
   | 
 
先 import 第三方的套件
- 套件在 github 必須先在終端機輸入以下指令下載,才能 import
 
 
1
   | go get github.com/julienschmidt/httprouter
   | 
 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
   | func index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { 	data := map[string]string{ 		"name":    "Guest", 		"someStr": "這是首頁", 	}
  	t, err := template.ParseFiles("./templates/index.html")
  	if err != nil { 		fmt.Println("首頁開啟錯誤 : ", err) 	}
  	t.Execute(w, data) }
  func hello(w http.ResponseWriter, r *http.Request, p httprouter.Params) { 	data := map[string]string{ 		"name":    p.ByName("name"), 		"someStr": "這是我的網站", 	}
  	t, err := template.ParseFiles("./templates/index.html")
  	if err != nil { 		fmt.Println("招呼頁開啟錯誤 : ", err) 	}
  	t.Execute(w, data) }
  func main() {
  	mux := httprouter.New()
  	mux.GET("/", index) 	mux.GET("/:name", hello)
  	fmt.Println("服務器即將開啟, 訪問地址 http://localhost:8080")
  	server := http.Server{ 		Addr:    ":8080", 		Handler: mux, 	}
  	err := server.ListenAndServe()
  	if err != nil { 		fmt.Println("服務器開啟錯誤 : ", err) 	} }
  | 
 
main
新增一個第三方的 route 物件
- 原本是用預設的,以下是新增物件使用預設 route 的寫法
 
 
1 2
   | mux := http.NewServeMux() mux.HandleFunc("/", index)
   | 
 
用 GET 來取得相對應函式
- 這邊的 
:name 為變數,在網址那邊可將變數傳入,例如 : http://localhost:8080/kenny,此時 name 就會是 kenny 
 
index
hello
需新增處理路徑變數的參數 p
- 將參數放入 map,網頁內容就會跟著你輸入的網址變數 
:name 來改變 
 
結果


