登录
首页 >  Golang >  Go问答

学会如何在不同模块中共享 Cookie 会话

来源:stackoverflow

时间:2024-02-08 22:18:22 171浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《学会如何在不同模块中共享 Cookie 会话》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

问题内容

我尝试为网站构建一个机器人。我的想法是,机器人具有很多功能,可以对网站执行一些操作,第一个操作是通过密码登录并保存会话。

我创建了一个登录函数,它从主函数调用并获取登录名和密码作为输入数据。然后我发送登录请求。然后我从响应中获取 cookie 并返回它。但是我应该如何应用cookie才能在其他功能中使用它们,以便网站将我视为授权用户,因为我返回cookie的数据格式不能在标头中替换,无论如何,我没有获得成功

func main() {

cookie := login("test", "test")
fmt.Println(cookie)



func login(email, password string) (cookie []*http.Cookie) {

loginLink := "https://oskelly.ru/api/v2/account/rawauth"

jar, _ := cookiejar.New(nil)
client := http.Client{Jar: jar}

resp, _ := client.PostForm(loginLink, url.Values{"rawEmail": {email}, "rawPassword": {password}})

body, _ := ioutil.ReadAll(resp.Body)

fmt.Println(string(body))

cookie = resp.Cookies()

return cookie

正确答案


您可以定义一个名为 bot 的新结构类型,然后将客户端存储在其中。从那里,您可以为执行各种操作的机器人定义接收器方法,这些方法可以作为结构中的字段访问您的 http 客户端。

请参阅 https://gobyexample.com/methods 作为此概念的基本示例。

编辑(在浏览器中写的,不能说它是否运行):

func main() {
    client := login("test", "test")
    client.DoSomething()
    client.DoSomethingElse() 
}

type WebClient struct {
    client *http.Client
    cookies []*http.Cookie
}

func NewWebClient(email, password string) (*WebClient) {
    var cookies []*http.Cookie
    loginLink := "https://oskelly.ru/api/v2/account/rawauth"
    jar, _ := cookiejar.New(nil)
    client := http.Client{Jar: jar}
    resp, _ := client.PostForm(
        loginLink, 
        url.Values{ "rawEmail": email, 
                    "rawPassword": password,
                  })
    body, _ := ioutil.ReadAll(resp.Body)
    cookies = resp.Cookies()
    return &WebClient{
                       client: &client, 
                       cookies: cookie,
                     }
}

func (c *WebClient) DoSomething() {
    // you can access the client and cookies you created earlier from here
    fmt.Printf("%+v\n", c.cookies)
}

func (c *WebClient) DoSomethingElse() {
    // you can access the client and cookies you created earlier from here
    fmt.Printf("%+v\n", c.cookies)
}

理论要掌握,实操不能落!以上关于《学会如何在不同模块中共享 Cookie 会话》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>