'How to create a cookie session that will be available in different functions?

I try to build a bot for website. My idea for bot with a lot of functions which do some actions with website and first action is login by password and save session.

I create a login function which calling from main and get login and password as input data. Then I send post request with login. Then I get cookie from response and return this. But how should I apply cookies in order to use them in other functions and so that the site perceives me as an authorized user because the data format in which I return cookies cannot be substituted in the header, in any case, I did not get success

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


Solution 1:[1]

You could define a new struct type named bot, then store the client in it. From there, you can define receiver methods for bot that perform your various operations, those methods would have access to your http client as a field in the struct.

See https://gobyexample.com/methods as a basic example of this concept.

Edit (wrote this in the browser, can't say if it runs):

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)
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1