Home >Backend Development >Golang >How to set cookies in golang
Golang is an emerging programming language that has advantages in simplicity and efficiency. How to use Golang to set cookies is a very important issue in web development. This article will introduce how to set cookies using Golang.
1. What is a cookie?
Before introducing how to set cookies in Golang, let’s first understand what cookies are. A cookie is a small piece of text information that is stored on the client (such as a browser) and is used to track user activities. When a user visits a website, the website can use cookies to store and read the user's data, such as the user's login information, shopping cart status, etc.
2. Setting cookies
In Golang, setting cookies requires using the SetCookie function in the net/http package. The SetCookie function is defined as follows:
func SetCookie(w ResponseWriter, cookie *Cookie)
Among them, w is the ResponseWriter interface type, which can be obtained through http.ResponseWriter. Cookie is a pointer of *http.Cookie type, indicating the cookie information to be set.
The code is as follows:
package main import ( "net/http" ) func main() { http.HandleFunc("/", setCookie) http.ListenAndServe(":8080", nil) } func setCookie(w http.ResponseWriter, r *http.Request) { cookie := &http.Cookie{ Name: "username", Value: "golang", Path: "/", MaxAge: 120, } http.SetCookie(w, cookie) w.Write([]byte("Cookie set successfully.")) }
The above code will set a cookie named "username", value "golang", path "/", and expiration time of 120 seconds to the client. (browser).
3. Obtain cookies
Obtaining cookies is also achieved through the Cookie function provided in the net/http package. The definition of the Cookie function is as follows:
func (r *Request) Cookie(name string) (*Cookie, error)
Among them, r is the Request structure type, indicating the request information, name is the name of the cookie, and the return value is a pointer of *http.Cookie type and a return value of error type.
The code is as follows:
package main import ( "fmt" "net/http" ) func main() { http.HandleFunc("/", getCookie) http.ListenAndServe(":8080", nil) } func getCookie(w http.ResponseWriter, r *http.Request) { cookie, err := r.Cookie("username") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } fmt.Fprintf(w, "Hello %s", cookie.Value) }
The above code will get the value of the cookie named "username" from the cookie of the client (browser) and display it on the web page.
4. Summary
This article introduces how to use Golang to set and obtain cookies. In web development, cookies are a very important technology, which can help websites track user activities and provide personalized services. I hope that readers can better master Golang's cookie technology by studying this article.
The above is the detailed content of How to set cookies in golang. For more information, please follow other related articles on the PHP Chinese website!