github.com/qiuhoude/go-web@v0.0.0-20220223060959-ab545e78f20d/prepare/03_form/demo01_loginserver.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"net/http"
     7  	"strings"
     8  	"text/template"
     9  )
    10  
    11  func sayHello(w http.ResponseWriter, r *http.Request) {
    12  	r.ParseForm()       //解析url传递的参数,对于POST则解析响应包的主体(request body)
    13  	fmt.Println(r.Form) //这些信息是输出到服务器端的打印信息
    14  	fmt.Println("path", r.URL.Path)
    15  	fmt.Println("scheme", r.URL.Scheme)
    16  	fmt.Println(r.Form["url_long"])
    17  	for k, v := range r.Form {
    18  		fmt.Println("key:", k)
    19  		fmt.Println("val:", strings.Join(v, ""))
    20  	}
    21  	fmt.Fprintf(w, "Hello my route!") //这个写入到w的是输出到客户端的
    22  
    23  }
    24  
    25  func login(w http.ResponseWriter, r *http.Request) {
    26  	r.ParseForm()
    27  	fmt.Println("method:", r.Method) //获取请求的方法
    28  	if r.Method == http.MethodPost {
    29  		//请求的是登陆数据,那么执行登陆的逻辑判断
    30  		fmt.Println("username:", r.Form["username"])
    31  		fmt.Println("password:", r.Form["password"])
    32  	} else if r.Method == http.MethodGet {
    33  		t, err := template.ParseFiles(`login.html`) // 解析文件模板
    34  		if err != nil {
    35  			log.Println(err)
    36  			return
    37  		}
    38  		t.Execute(w, "登陆页面")
    39  	}
    40  }
    41  
    42  func main() {
    43  	http.HandleFunc("/hello", sayHello)
    44  	http.HandleFunc("/login", login)
    45  	err := http.ListenAndServe(":8000", nil)
    46  	if err != nil {
    47  		log.Fatal("ListenAndServe: ", nil)
    48  	}
    49  }