go使用cookie实现闪现消息

2019-02-13  本文已影响0人  乘风破浪_6a9f
package main

import (
    "net/http"
    "encoding/base64"
    "fmt"
    "time"
)

func setMessage(w http.ResponseWriter,r *http.Request){
    msg :=[]byte("hello world!")
    c := http.Cookie{
        Name :"flash",
        Value:base64.URLEncoding.EncodeToString(msg),
    }
    http.SetCookie(w,&c)
}

func showMessage(w http.ResponseWriter, r *http.Request)  {
    c ,err := r.Cookie("flash")
    if err != nil {
        if err == http.ErrNoCookie {
            fmt.Fprintln(w,"No message found")
        }
    } else {
        rc := http.Cookie{
            Name : "flash",
            MaxAge : -1,
            Expires:time.Unix(1,0),
        }
        http.SetCookie(w,&rc)
        val,_:=base64.URLEncoding.DecodeString(c.Value)
        fmt.Fprintln(w,string(val))
    }
}

func main()  {
    server := http.Server{
        Addr:"127.0.0.1:8080",
    }
    http.HandleFunc("/set_message",setMessage)
    http.HandleFunc("/show_message",showMessage)
    server.ListenAndServe()
}
上一篇下一篇

猜你喜欢

热点阅读