7.5 Cookie

设置cookie

  1. package main
  2. import (
  3. "log"
  4. "net/http"
  5. )
  6. func sayHelloHandler(w http.ResponseWriter, r *http.Request) {
  7. SetCookie(w, r)
  8. //fmt.Fprintf(w, "Hello world!\n") //这个写入到w的是输出到客户端的
  9. }
  10. func main() {
  11. http.HandleFunc("/", sayHelloHandler) // 设置访问路由
  12. log.Fatal(http.ListenAndServe(":8080", nil))
  13. }
  14. func SetCookie(w http.ResponseWriter, r *http.Request) {
  15. ck := &http.Cookie{
  16. Name: "name",
  17. Value: "hello",
  18. Path: "/",
  19. Domain: "localhost",
  20. MaxAge: 120,
  21. }
  22. w.Header().Set("set-cookie", ck.String()) //设置cookie value 值可以包含空格
  23. //http.SetCookie(w, ck) //设置cookie value 值可以不能包含空格
  24. }

读取cookie

  1. cookie, err := r.Cookie("name")
  2. if err == nil {
  3. fmt.Println(cookie.Value)
  4. fmt.Println(cookie.Domain)
  5. fmt.Println(cookie.Expires)
  6. }

links