Go web form

package main
import (
	"fmt"
	"html/template"
	"log"
	"net/http"
	"strings"
)
func sayhelloName(w http.ResponseWriter,r *http.Request){ //Access body response
	r.ParseForm() //Parse the parameters passed by the url, and parse the body of the response packet for POST
	//If the ParseForm method is not called, the data of the form cannot be obtained.
	fmt.Println(r.Form)//Output the parameters of the url to the server
	fmt.Println(r.URL.Path)//The path of the output url
	fmt.Println(r.URL.Scheme)//Output scheme
	for k,v :=range r.Form{
		fmt.Println (k)
		fmt.Println(strings.Join(v,""))//Add string output to see the effect
	}
	fmt.Fprintf(w,"hello world")//Response content
}
func login(w http.ResponseWriter,r *http.Request){
	fmt.Println(r.Method)//The method of outputting the client request
	if r.Method=="GET"{
		t,_:=template.ParseFiles("login.html") //Parse the html code, which is the form
		log.Println(t.Execute(w,nil))
	}else{
		r.ParseForm()
		fmt.Println(r.Form["username"]) //The dictionary gets the value of username
		fmt.Println(r.Form["password"])
	}
}

func main(){
	http.HandleFunc("/",sayhelloName) //Set the route for access
	http.HandleFunc("/login",login)
	err:=http.ListenAndServe(":9999",nil)//Set the listening port
	if err !=nil{
		log.Fatal("listenandserver",err)//If an error is reported, output an error and exit
	}
}

  

<html>
<head>
<title></title>
</head>
<body>
<form action="/login" method="post">
	用户名:<input type="text" name="username">
	密码:<input type="password" name="password">
	<input type="submit" value="登录">
</form>
</body>
</html>

  

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325384136&siteId=291194637