美文网首页
go使用cookie实现闪现消息

go使用cookie实现闪现消息

作者: 乘风破浪_6a9f | 来源:发表于2019-02-13 15:56 被阅读0次
    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()
    }
    

    相关文章

      网友评论

          本文标题:go使用cookie实现闪现消息

          本文链接:https://www.haomeiwen.com/subject/svsdeqtx.html