在使用 Golang 设置跨子域的 Cookie 时,你需要确保以下步骤:
- 在服务器端设置允许跨域请求,包括设置适当的 CORS(Cross-Origin Resource Sharing)响应头。可以通过
Access-Control-Allow-Origin
来指定允许跨域请求的源。 - 在设置 Cookie 时,确保指定了
Domain
字段为主域名以及子域名的共享父级域名。这样可以使得该 Cookie 能够被多个子域名所共享。
下面是一个示例代码片段,展示了如何在 Golang 中进行跨子域设置 Cookie:
package main
import (
"net/http"
)
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
func handler(w http.ResponseWriter, r *http.Request) {
// 设置允许跨域请求
w.Header().Set("Access-Control-Allow-Origin", "http://example.com") // 替换成实际允许的源
// 设置 Cookie
cookie := http.Cookie{
Name: "my-cookie",
Value: "cookie-value",
Path: "/",
Domain: ".example.com", // 替换成实际的共享父级域名
HttpOnly: true,
}
http.SetCookie(w, &cookie)
w.Write([]byte("Cookie set successfully"))
}
请注意替换示例中的实际允许的源和共享父级域名。此外,还可以根据需要设置其他 Cookie 属性,例如 MaxAge
、Secure
等。
内容由零声教学AI助手提供,问题来源于学员提问