- http语句
net/http
html/template
func home(w http.ResponseWriter, r *http.Request){
w.Header().Set("Access-Control-Allow-Origin", "*") 跨域
fmt.Fprintf(w,"%#v\n", r.UserAgent()) //"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 Edg/87.0.664.66"
r.Host //localhost:8081
r.Method //GET 或者POST
fmt.Fprintf(w,"%#v\n", r)
fmt.Fprintf(w, "Hello astaxie!")
t, _ := template.ParseFiles("login.gtpl")
log.Println(t.Execute(w, nil))
fmt.Println("username:", r.FormValue("username"))
fmt.Println("username:", r.Form["username"])
普通模板
t := template.Must(template.ParseFiles("index.html"))
t.Execute(w, "")
// embed方式
t := template.Must(template.ParseFS(dir,"ui/index.html"))
t.Execute(w, "")
}
http.HandleFunc("/", home) 路由
http.Redirect(w, r, "/foo", 302) 内部跳转
http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("ui/css/")))) //静态路由服务器,将模板路径中css替换成真实路径ui/css中文件
http.Handle("/ui/",http.FileServer(http.FS(dir))) // //go:embed ui var dir embed.FS embed使用
http.ListenAndServe(":8080", nil) //设置监听的端口
GET请求
resp, _ := http.Get("http://api.baidu.com/user/info?id=1")
defer resp.Body.Close()
content, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(content))
POST提交
post:=url.Values{"aa":[]string{"w"}}
post.Add("id", "1")
resp, _ := http.PostForm("test.php", post)
defer resp.Body.Close()
content, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(content))
post.Encode() id=1&aa=w
data := strings.NewReader("username=tizi&password=1234")
resp, err := http.Post("t.go","application/x-www-form-urlencoded", data)
req, _ := http.NewRequest("POST", "t.go",data)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
- cookie
写cookie
expiration := time.Now()
expiration = expiration.AddDate(1, 0, 0)
cookie := http.Cookie{Name: "username", Value: "astaxie", Expires: expiration}
http.SetCookie(w, &cookie)
读取cookie
cookie, _ := r.Cookie("username")
fmt.Fprint(w, cookie)
for _, cookie := range r.Cookies() {
fmt.Fprint(w, cookie.Name)
}
- http常量
http.StatusOK=200 成功
http.StatusMovedPermanently=301 跳转
http.StatusBadRequest=400 错误
http.StatusUnauthorized=401 未授权
http.StatusForbidden=403 禁止访问
http.StatusNotFound=404 未找到
url.QueryEscape(str) urlencode
url.QueryEscape(str) urldecode
b64 := base64.StdEncoding.EncodeToString([]byte("123")) //编译base64
fmt.Println(b64)
b64de, _ := base64.StdEncoding.DecodeString(b64) //解析base64
fmt.Println(string(b64de))
uEnc := base64.URLEncoding.EncodeToString([]byte("123")) //url编译base64
fmt.Println(uEnc)
uDec, _ := base64.URLEncoding.DecodeString(uEnc) //解析urlbase64
fmt.Println(string(uDec))
作者:Yoby 创建时间:2020-09-23 21:53
更新时间:2024-12-05 13:26
更新时间:2024-12-05 13:26