[GO] GO를 사용하여 쿠키로 FlashMessage 만들기
1. 쿠키 만들기
먼저 쿠키를 만듭니다.
func setMessage(w http.ResponseWriter, r *http.Request) {
    msg := []byte("Hello World")
   //ヘッダ内ではクッキーの値をURLエンコードする必要があるらしい
    c := http.Cookie{
      Name:   "Qiita",
      Value: base64.URLEncoding.EncodeToString(msg),
    HttpOnly: true
    }
    http.SetCookie(w, &c)
}
2. 쿠키를 기반으로 플래시 메시지 만들기
func showMessage(w http.ResponseWriter, r *http.Request){
   //構造体Requestの中には名前付きクッキーを取り出せるCookieメソッドがある。
  //Name: "Qiita"のクッキーを探す、ない場合はerrにエラー文が入る。
    c, err := r.Cookie("Qiita")
    if err != nil {
        if err == http.ErrNoCookie{
            fmt.Fprintln(w, "メッセージがありません")
            //fmt.Fprintln(w, err)
            //エラー文が見たい人は上のコメントアウト外してみて
        }
    } else {
        rc := http.Cookie{
            Name: "Qiita",
            MaxAge: -1,
            Expires: time.Unix(1,0),
        }
        http.SetCookie(w, &rc)
        val, _ := base64.URLEncoding.DecodeString(c.Value)
        fmt.Fprintln(w, string(val))
    }
}
3. 만든 핸들러 함수(showMessage, setMessage)를 핸들러로 변환, 멀티플렉서에 뿌린다
func main() {
    server := http.Server{
        Addr: "127.0.0.1:8080",
    }
    http.HandleFunc("/set_message", setMessage)
    http.HandleFunc("/show_message", showMessage)
    server.ListenAndServe()
}
완성형
main.gopackage main
import (
"encoding/base64"
"fmt"
"net/http"
"time"
)
func setMessage(w http.ResponseWriter, r *http.Request){
    msg := []byte("Hello World")
    c := http.Cookie{
        Name: "Qiita",
        Value: base64.URLEncoding.EncodeToString(msg),
    }
    http.SetCookie(w, &c)
}
func showMessage(w http.ResponseWriter, r *http.Request){
    //名前付きクッキーを取り出すメソッドCookie、指定したクッキーがないときエラーを返す
    c, err := r.Cookie("Qiita")
    //Name: "cookie"のcookieの構造体が存在しないとエラー文"http: named cookie not present"が送られてくる。
    if err != nil {
        if err == http.ErrNoCookie{
            fmt.Fprintln(w, "メッセージがありません")
            fmt.Fprintln(w, err)
        }
    } else {
        rc := http.Cookie{
            Name: "Qiita",
            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 build main.go
$./main
http://127.0.0.1.8080/set_message 를 열어보세요.
Chrome 검증 기능을 사용하여 쿠키가 만들어 졌음을 확인할 수 있습니다.
 
그런 다음 http://127.0.0.1:8080/show_message 를 열어보십시오.
 Hello World
그리고 나왔습니까?
 
검증 기능을 사용하면 쿠키가 사라지고 있음을 알 수 있습니다.
 마지막으로 쿠키의 구조체 (모델) 올려 둡니다 ~
Cookie_struct.gotype Cookie struct{
 Name:           string
 Value:          string
 Path:           string
 Domain:         string
 Expires:        time.Time
 RawExpires:     string
 MaxAge:         int
 Secure:         bool
 HttpOnly:       bool
 Raw:            string
 Unparsed:       []string
}
                
                    
        
    
    
    
    
    
                
                
                
                
                    
                        
                            
                            
                            Reference
                            
                            이 문제에 관하여([GO] GO를 사용하여 쿠키로 FlashMessage 만들기), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
                                
                                https://qiita.com/gonza_kato_atsushi/items/97193908798b86284a25
                            
                            
                            
                                텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                            
                            
                                
                                
                                 우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)
                            
                            
                        
                    
                
                
                
            
package main
import (
"encoding/base64"
"fmt"
"net/http"
"time"
)
func setMessage(w http.ResponseWriter, r *http.Request){
    msg := []byte("Hello World")
    c := http.Cookie{
        Name: "Qiita",
        Value: base64.URLEncoding.EncodeToString(msg),
    }
    http.SetCookie(w, &c)
}
func showMessage(w http.ResponseWriter, r *http.Request){
    //名前付きクッキーを取り出すメソッドCookie、指定したクッキーがないときエラーを返す
    c, err := r.Cookie("Qiita")
    //Name: "cookie"のcookieの構造体が存在しないとエラー文"http: named cookie not present"が送られてくる。
    if err != nil {
        if err == http.ErrNoCookie{
            fmt.Fprintln(w, "メッセージがありません")
            fmt.Fprintln(w, err)
        }
    } else {
        rc := http.Cookie{
            Name: "Qiita",
            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 build main.go
$./main
http://127.0.0.1.8080/set_message 를 열어보세요.Chrome 검증 기능을 사용하여 쿠키가 만들어 졌음을 확인할 수 있습니다.

그런 다음
http://127.0.0.1:8080/show_message 를 열어보십시오.Hello World
그리고 나왔습니까?

검증 기능을 사용하면 쿠키가 사라지고 있음을 알 수 있습니다.
마지막으로 쿠키의 구조체 (모델) 올려 둡니다 ~
Cookie_struct.gotype Cookie struct{
 Name:           string
 Value:          string
 Path:           string
 Domain:         string
 Expires:        time.Time
 RawExpires:     string
 MaxAge:         int
 Secure:         bool
 HttpOnly:       bool
 Raw:            string
 Unparsed:       []string
}
                
                    
        
    
    
    
    
    
                
                
                
                
                    
                        
                            
                            
                            Reference
                            
                            이 문제에 관하여([GO] GO를 사용하여 쿠키로 FlashMessage 만들기), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
                                
                                https://qiita.com/gonza_kato_atsushi/items/97193908798b86284a25
                            
                            
                            
                                텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                            
                            
                                
                                
                                 우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)
                            
                            
                        
                    
                
                
                
            
type Cookie struct{
 Name:           string
 Value:          string
 Path:           string
 Domain:         string
 Expires:        time.Time
 RawExpires:     string
 MaxAge:         int
 Secure:         bool
 HttpOnly:       bool
 Raw:            string
 Unparsed:       []string
}
Reference
이 문제에 관하여([GO] GO를 사용하여 쿠키로 FlashMessage 만들기), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/gonza_kato_atsushi/items/97193908798b86284a25텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)