website - skynocover/Wiki-for-GoLang GitHub Wiki

基本建立

func main() {
	http.HandleFunc("/", handler) // each request calls handler
	http.ListenAndServe("localhost:8123", nil)
}
func handler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "URL.Path = %q\n", r.URL.Path) //r.URL.Path會取的網址後面輸入的文字
}

網址(http://localhost:8123/)
在網頁後面加上數字會顯示所在的位置


r.URL.Query

func main() {
	http.HandleFunc("/", handler)
	http.ListenAndServe(":3000", nil)
}

func handler(w http.ResponseWriter, r *http.Request) {

	keys, ok := r.URL.Query()["key"]
	if !ok || len(keys[0]) < 1 {
		fmt.Fprint(w, "Url Param 'key' is missing")
		return
	}

	key := keys[0]
	fmt.Fprint(w, "Url Param 'key' is: "+string(key))
}

r.URL.Query()["key"]

  • 會去搜尋key對應的值
http://localhost:3000/?key=abc
> Url Param 'key' is: abc
http://localhost:3000/?shop=1&key=abc&page=1
> Url Param 'key' is: abc //參數的數量與位置不會影響
http://localhost:3000/key/abc
> Url Param 'key' is missing //無法處理這種形式的參數

?到key中間不算,之後的值一直到&會被抓出來


基本登錄畫面

func main() {
	http.HandleFunc("/login", login)
	err := http.ListenAndServe(":3000", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}

func login(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	fmt.Println("method:", r.Method)
	if r.Method == "GET" {
		t, _ := template.ParseFiles("./login.html")
		log.Println(t.Execute(w, nil))
	} else {
		// 在這邊放真實的驗證
		fmt.Fprint(w, "username: ", r.Form["username"][0])
		fmt.Fprint(w, ", password: ", r.Form["password"][0])
	}
}
  • w post的路由
  • r get的路由

r.ParseForm()
解析request內POST的主體,並且把參數讀取出來 若沒宣告就讀不到

r.Method
可以將action讀出來,並自動判斷現在是post還是get

<html>
  <head>
    <title></title>
  </head>
  <body>
    <form action="/login" method="post">
      Username:<input type="text" name="username">
      Password:<input type="password" name="password">
      <input type="submit" value="Submit">
    </form>
  </body>
</html>

進階登錄畫面

type ContactDetails struct {
	Email   string
	Subject string
	Message string
}

func main() {
	http.HandleFunc("/", handler)
	http.ListenAndServe(":3000", nil)
}

func handler(w http.ResponseWriter, r *http.Request) {
	tmpl := template.Must(template.ParseFiles("./login.html"))
	if r.Method != http.MethodPost {
		tmpl.Execute(w, nil)
		return
	}

	details := ContactDetails{
		Email:   r.FormValue("email"),
		Subject: r.FormValue("subject"),
		Message: r.FormValue("message"),
	}

	// do something with details
	_ = details
	log.Println("Email:" + details.Email)
	log.Println("Subject:" + details.Subject)
	log.Println("Message:" + details.Message)
	tmpl.Execute(w, struct{ Success bool }{true})
}

template.Must讀取經過template.ParseFiles解析過的網頁
之後就可以讓html跟go互動
{{內部的邏輯在此}}

{{if .Success}}
	<h1>Thanks for your message!</h1>
{{else}}
	<h1>Contact</h1>
	<form method="POST">
		<label>Email:</label><br />
		<input type="text" name="email"><br />
		<label>Subject:</label><br />
		<input type="text" name="subject"><br />
		<label>Message:</label><br />
		<textarea name="message"></textarea><br />
		<input type="submit">
	</form>
{{end}}
⚠️ **GitHub.com Fallback** ⚠️