• 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))
  • router
  • session
"github.com/go-session/redis"
"github.com/go-session/session"

session.InitManager(
        session.SetStore(redis.NewRedisStore(&redis.Options{
            Addr: "127.0.0.1:6379",
            DB:   0,
        })),
    )
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        store, _ := session.Start(context.Background(), w, r)
        store.Set("foo", "中国ok")
        store.Save()
        http.Redirect(w, r, "/foo", 302)
    })
    http.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) {
        store, _ := session.Start(context.Background(), w, r)
        foo, ok := store.Get("foo")
        if ok {
            fmt.Fprintf(w, "foo:%s", foo)
            return
        }
        fmt.Fprint(w, "does not exist")
    })
"github.com/go-session/buntdb"   //其他都一样,存储到本地字符串
session.InitManager(
        session.SetStore(buntdb.NewFileStore("session.db")),
    )
"github.com/go-session/cookie"
    session.InitManager(
        session.SetStore(
            cookie.NewCookieStore(
                cookie.SetCookieName("demo_cookie_store_id"),
                cookie.SetHashKey([]byte("FF51A553-72FC-478B-9AEF-93D6F506DE91")),
            ),
        ),
    )
文档更新时间: 2021-11-29 20:05   作者:Yoby