Go HTTP Post and Use Cookies
Problem: Integrating cookies into a Go application to facilitate website login and subsequent page access.
Consider the following sample code:
func Login(user, password string) string { postUrl := "http://www.pge.com/eum/login" values := make(url.Values) values.Set("user", user) values.Set("password", password) resp, err := http.PostForm(postUrl, values) if err != nil { log.Fatal(err) } defer resp.Body.Close() // Store cookies here! return "Hello" } func ViewBill(url string, cookies) string { // Access page using cookies! }
Solution: In Go, cookie management was introduced in version 1.1 via the net/http/cookiejar package.
Enhance your code with cookie handling capabilities:
import ( "net/http" "net/http/cookiejar" ) jar, err := cookiejar.New(nil) if err != nil { // Handle error } client := &http.Client{ Jar: jar, }
This client adorned with the Jar implementation of the cookie jar can now store cookies for use during subsequent requests, facilitating smooth login and page navigation.
The above is the detailed content of How to Manage Cookies in Go HTTP POST Requests for Website Login and Page Access?. For more information, please follow other related articles on the PHP Chinese website!