Cookies (HTTP Cookies) are used to store data on the client side, for example, for authentication, session management, or content personalization. In the Go language, working with cookies is implemented through the standard net/http library, which makes their use simple and convenient. In this article, we will look at the basic operations with cookies in Go, and also consider aspects of their security.
Basic Cookie Operations in Go
Setting cookies
To set a cookie in the server response, you need to use the Set-Cookie header. In Go, you use http.SetCookie() for this:
package main
import (
"net/http"
)
func setCookieHandler(w http.ResponseWriter, r *http.Request) {
cookie := &http.Cookie{
Name: "session_id",
Value: "123456",
Path: "/",
HttpOnly: true,
Secure: true,
SameSite: http.SameSiteStrictMode,
}
http.SetCookie(w, cookie)
w.Write([]byte("Cookie set!"))
}
func main() {
http.HandleFunc("/set-cookie", setCookieHandler)
http.ListenAndServe(":8080", nil)
}
This handler sets the session_id cookie with secure parameters:
- HttpOnly: true — will prohibit access to cookies from JavaScript (protection against XSS attacks).
- Secure: true — the cookie will be transmitted only via HTTPS.
- SameSite: Strict - protection against CSRF attacks.
Reading cookies
Cookies are passed in the Cookie header and are available in http.Request via the r.Cookie() method:
func getCookieHandler(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("session_id")
if err != nil {
http.Error(w, "Cookie not found", http.StatusNotFound)
return
}
w.Write([]byte("Cookie value: " + cookie.Value))
}
func main() {
http.HandleFunc("/get-cookie", getCookieHandler)
http.ListenAndServe(":8080", nil)
}
Deleting cookies
To delete a cookie, you need to set it with an expired date:
func deleteCookieHandler(w http.ResponseWriter, r *http.Request) {
cookie := &http.Cookie{
Name: "session_id",
Value: "",
Path: "/",
MaxAge: -1,
}
http.SetCookie(w, cookie)
w.Write([]byte("Cookie deleted!"))
}
Cookie Security
HttpOnly and Secure
Using HttpOnly and Secure prevents cookies from being stolen via JavaScript (document.cookie) and protects them from being transmitted over HTTP.
SameSite and CSRF
SameSite protects against CSRF attacks:
- Lax - cookies are sent only when clicking through a link.
- Strict - cookies are sent only when browsing within a single domain.
- None - cookies are always transmitted, but only with Secure: true.
Signing and Encrypting Cookies
To protect the contents of cookies, you can use gorilla/securecookie:
import (
"encoding/gob"
"github.com/gorilla/securecookie"
)
var hashKey = []byte("super-secret-key")
var s = securecookie.New(hashKey, nil)
type SessionData struct {
Username string
}
gob.Register(SessionData{})
func setSignedCookie(w http.ResponseWriter) {
value := SessionData{Username: "user123"}
encoded, _ := s.Encode("session", value)
cookie := &http.Cookie{Name: "session", Value: encoded, Path: "/", HttpOnly: true}
http.SetCookie(w, cookie)
}
Conclusion
Working with cookies in Go is easy, but requires attention to security. Using HttpOnly, Secure, SameSite, and data signing help protect against attacks and data leaks. If you need secure authentication, consider alternatives like JWT or server sessions.
You can test the code by running the server at http://localhost:8080 and checking for setting, getting and deleting cookies.