#development #golang #http #laravel #php

If you want to do multiple HTTP requests in a row using the HTTP client from Laravel and persist cookies between them, you can use a cookie jar. This is a class that stores cookies and sends them back to the server when needed. Here's how you can use it:

 1use GuzzleHttp\Cookie\CookieJar;
 2use Illuminate\Support\Facades\Http;
 3
 4// Create a cookie jar to store cookies
 5$cookieJar = new CookieJar();
 6
 7// Create a new HTTP client with the cookie jar
 8// You can also set other options here, like the base URL or whether to follow redirects
 9$client = Http::baseUrl('https://www.mywebsite.com')
10    ->withOptions(['cookies' => $cookieJar])
11    ->withoutRedirecting()
12    ->throw();
13
14// Make a request that sets a cookie (e.g., logging in)
15$authResp = $client->asForm()->post(
16    url: '/login',
17    data: [
18        'username' => 'username',
19        'password' => 'password',
20    ]
21);
22
23// Store the cookies from the response in the cookie jar
24$cookies = $authResp->cookies();
25foreach ($cookies as $cookie) {
26    $cookieJar->setCookie($cookie);
27}
28
29// Make another request that requires authentication (which relies on the cookies being present)
30$authenticatedResponse = $client->get('/authenticated-page');

If you want to do the same in Golang, you can do this:

 1package main
 2
 3import (
 4    "bytes"
 5    "fmt"
 6    "net/http"
 7    "net/http/cookiejar"
 8    "net/url"
 9)
10
11func main() {
12    // Create a cookie jar to store cookies
13    cookieJar, _ := cookiejar.New(nil)
14
15    // Create a new HTTP client with the cookie jar
16    client := &http.Client{
17        Jar: cookieJar, // Use this cookie jar
18        CheckRedirect: func(req *http.Request, via []*http.Request) error {
19            return http.ErrUseLastResponse // Don't follow redirects
20        },
21    }
22
23    // Create a request body with the login credentials
24    params := url.Values{}
25    params.Set("username", "username")
26    params.Set("password", "password")
27    body := bytes.NewBufferString(params.Encode())
28
29    // Make a request that sets a cookie (e.g., logging in)
30    // The response cookies will automatically be stored in the cookie jar
31    authReq, _ := http.NewRequest(http.MethodPost, "https://www.mywebsite.com/login", body)
32    _, _ = client.Do(authReq)
33
34    // Make another request that requires authentication (which relies on the cookies being present)
35    authenticatedReq, _ := http.NewRequest(http.MethodGet, "https://www.mywebsite.com/authenticated-page", nil)
36    authenticatedResp, _ := client.Do(authenticatedReq)
37    defer authenticatedResp.Body.Close()
38
39    // Print the response status and headers
40    fmt.Println("response Status : ", authenticatedResp.Status)
41    fmt.Println("response Headers : ", authenticatedResp.Header)
42}