一、server
package main
import (
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
)
func main() {
http.HandleFunc("/login",login)
err := http.ListenAndServe(":2001", nil)
if err != nil {
log.Fatal(err)
}
}
func login(w http.ResponseWriter,r *http.Request) {
r.ParseForm()
bytes, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Fatal(err)
}
r.Body.Close()
fmt.Println("Body:",string(bytes))
fmt.Printf("r=%+v\n",r)
fmt.Printf("r.Header=%+v\n",r.Header)
fmt.Printf("Content-Type=%+v\n",r.Header["Content-Type"])
fmt.Printf("r.Cookies()=%+v\n",r.Cookies())
//打印Cookie信息
cookie, err := r.Cookie("userId")
if err == nil {
//打印cookie信息
fmt.Println(cookie.Name,cookie.Value)
}
if len(r.Form["username"]) > 0 {
username := r.Form["username"][0]
fmt.Println("username:",username)
}
if len(r.Form["password"]) > 0 {
password := r.Form["password"][0]
fmt.Println("password",password)
}
io.WriteString(w,"登录成功")
}
二、cilent
package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
)
func main() {
urls := "http://localhost:2001/login"
client := http.Client{}
param := url.Values{
"username" : {"kkkk"},
}
requestBody := bytes.NewBufferString(param.Encode())
request, err := http.NewRequest("POST", urls, requestBody)
if err != nil {
log.Fatal(err)
}
//cookie的添加方式一
cookId := &http.Cookie{Name:"userId",Value:"1234"}
cookieName := &http.Cookie{Name: "name", Value: "456"}
request.AddCookie(cookId)
request.AddCookie(cookieName)
//cookie的添加方式二
request.Header.Set("Content-Type","application/x-www-form-urlencoded")
response, err := client.Do(request)
if err != nil {
log.Fatal(err)
}
defer response.Body.Close()
if response.StatusCode == 200 {
all, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(all))
}
fmt.Printf("response:%+v\n",response)
fmt.Printf("response.Header:%+v\n",response.Header)
}
三、设置cookie
package main
import (
"fmt"
"net/http"
)
func SetCookie(w http.ResponseWriter,r *http.Request) {
//设置cookie
cookie := http.Cookie{
Name: "name",
Value: "laowang",
Path: "/",
MaxAge: 30,
}
http.SetCookie(w,&cookie)
w.Write([]byte("write cookie ok"))
}
func GetCookie(w http.ResponseWriter,r *http.Request) {
//读取cookie
cookie, _ := r.Cookie("name")
fmt.Fprint(w,cookie)
}
func main() {
http.HandleFunc("/SetCookie",SetCookie)
http.HandleFunc("/GetCookie",GetCookie)
http.ListenAndServe(":8080",nil)
}