📌  相关文章
📜  http only cookie - Go 编程语言(1)

📅  最后修改于: 2023-12-03 15:01:19.639000             🧑  作者: Mango

HTTP Only Cookie in Go

HTTP-only cookies are a type of cookie that can be set by a server and can only be accessed by the server through HTTP or HTTPS protocols, but not via JavaScript, making them more secure against cross-site scripting (XSS) attacks. In this article, we will explore how to set and use HTTP-only cookies in Go.

Setting HTTP-only Cookies

In Go, you can set HTTP-only cookies using the net/http package. Here is an example:

package main

import (
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        cookie := &http.Cookie{
            Name:     "mycookie",
            Value:    "myvalue",
            HttpOnly: true,
        }
        http.SetCookie(w, cookie)
        w.Write([]byte("Cookie set successfully!"))
    })

    http.ListenAndServe(":8000", nil)
}

In this example, we set a cookie named mycookie with the value myvalue. The HttpOnly field is set to true to make it an HTTP-only cookie. The http.SetCookie() method is used to set the cookie in the response header. The w.Write() method is used to send a response message to the client.

Retrieving HTTP-only Cookies

Retrieving an HTTP-only cookie in Go is similar to retrieving a regular cookie. Here is an example:

package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        cookie, err := r.Cookie("mycookie")
        if err != nil {
            http.Error(w, err.Error(), http.StatusBadRequest)
            return
        }
        fmt.Fprintf(w, "Cookie value: %s", cookie.Value)
    })

    http.ListenAndServe(":8000", nil)
}

In this example, we retrieve the cookie named mycookie using the r.Cookie() method. If the cookie is not found, we return a BadRequest error. If the cookie is found, we send the cookie value back to the client using fmt.Fprintf().

Conclusion

HTTP-only cookies are an important security feature that can help protect against XSS attacks. Go makes it easy to set and retrieve HTTP-only cookies using the net/http package. By using HTTP-only cookies, you can help make your web applications more secure.