W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
?HTTP
?客戶端發(fā)起請求時可以自定義發(fā)送給服務(wù)端的?Cookie
?內(nèi)容,該特性使用?SetCookie*
?相關(guān)方法實現(xiàn)。
方法列表:
func (c *Client) SetCookie(key, value string) *Client
func (c *Client) SetCookieMap(m map[string]string) *Client
我們來看一個客戶端自定義?Cookie
?的示例。
package main
import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
)
func main() {
s := g.Server()
s.BindHandler("/", func(r *ghttp.Request){
r.Response.Write(r.Cookie.Map())
})
s.SetPort(8199)
s.Run()
}
由于是作為示例,服務(wù)端的邏輯很簡單,直接將接收到的?Cookie
?參數(shù)全部返回給客戶端。
SetCookie
?方法package main
import (
"fmt"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gctx"
)
func main() {
c := g.Client()
c.SetCookie("name", "john")
c.SetCookie("score", "100")
if r, e := c.Get(gctx.New(), "http://127.0.0.1:8199/"); e != nil {
panic(e)
} else {
fmt.Println(r.ReadAllString())
}
}
通過?g.Client()
?創(chuàng)建一個自定義的?HTTP
?請求客戶端對象,并通過?c.SetCookie
?方法設(shè)置自定義的?Cookie
?,這里我們設(shè)置了兩個示例用的?Cookie
?參數(shù),一個?name
?,一個?score
?。
SetCookieMap
?方法
這個方法更加簡單,可以批量設(shè)置?Cookie
?鍵值對。
package main
import (
"fmt"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gctx"
)
func main() {
c := g.Client()
c.SetCookieMap(g.MapStrStr{
"name": "john",
"score": "100",
})
if r, e := c.Get(gctx.New(), "http://127.0.0.1:8199/"); e != nil {
panic(e)
} else {
fmt.Println(r.ReadAllString())
}
}
客戶端代碼執(zhí)行后,終端將會打印出服務(wù)端的返回結(jié)果,如下:
map[name:john score:100]
可以看到,服務(wù)端已經(jīng)接收到了客戶端自定義的?Cookie
?參數(shù)。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: