net / http로 쿠키 설정
Go의 net / http 패키지로 쿠키를 설정하려고합니다. 나는 가지고있다:
package main
import "io"
import "net/http"
import "time"
func indexHandler(w http.ResponseWriter, req *http.Request) {
expire := time.Now().AddDate(0, 0, 1)
cookie := http.Cookie{"test", "tcookie", "/", "www.domain.com", expire, expire.Format(time.UnixDate), 86400, true, true, "test=tcookie", []string{"test=tcookie"}}
req.AddCookie(&cookie)
io.WriteString(w, "Hello world!")
}
func main() {
http.HandleFunc("/", indexHandler)
http.ListenAndServe(":80", nil)
}
'쿠키'로 'Golang'검색을 시도했지만 좋은 결과를 얻지 못했습니다. 누구든지 올바른 방향으로 나를 가리킬 수 있다면 대단히 감사하겠습니다.
저는 Go 전문가는 아니지만 요청에 따라 쿠키를 설정하고있는 것 같습니다. 응답에 설정할 수 있습니다. setCookie
net / http에 기능 이 있습니다 . 도움이 될 수 있습니다 : http://golang.org/pkg/net/http/#SetCookie
func SetCookie(w ResponseWriter, cookie *Cookie)
//ShowAllTasksFunc is used to handle the "/" URL which is the default ons
func ShowAllTasksFunc(w http.ResponseWriter, r *http.Request){
if r.Method == "GET" {
context := db.GetTasks("pending") //true when you want non deleted notes
if message != "" {
context.Message = message
}
context.CSRFToken = "abcd"
message = ""
expiration := time.Now().Add(365 * 24 * time.Hour)
cookie := http.Cookie{Name: "csrftoken",Value:"abcd",Expires:expiration}
http.SetCookie(w, &cookie)
homeTemplate.Execute(w, context)
} else {
message = "Method not allowed"
http.Redirect(w, r, "/", http.StatusFound)
}
}
Requests
와 사이에는 기본적인 차이가 있습니다 ResponseWriter
. 요청은 브라우저가 보내는 것과 같습니다.
Host: 127.0.0.1:8081
User-Agent: ...
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Referer: http://127.0.0.1:8081/
Cookie: csrftoken=abcd
Connection: keep-alive
응답은 핸들러가 보낼 것입니다.
Content-Type: text/html; charset=utf-8
Date: Tue, 12 Jan 2016 16:43:53 GMT
Set-Cookie: csrftoken=abcd; Expires=Wed, 11 Jan 2017 16:43:53 GMT
Transfer-Encoding: chunked
<html>...</html>
When the browser will make a request, it'll include the cookie for that domain, since cookies are stored domain wise and can't be accessed from cross domains, if you set a cookie as HTTP only then it can only be accessed from the website which set it via HTTP and not via JS.
So when getting information from cookies you can do that from the r.Cookie method, like this
cookie, _ := r.Cookie("csrftoken")
if formToken == cookie.Value {
https://github.com/thewhitetulip/Tasks/blob/master/views/addViews.go#L72-L75
But when you are going to set a cookie, you have to do it in the response writer method, the request is a read only object which we respond to, think of it as a text message you get from someone, that is a request, you can only get it, what you type is a response, so you can type in a cookie at
for more details: https://thewhitetulip.gitbooks.io/webapp-with-golang-anti-textbook/content/content/2.4workingwithform.html
This Below code helps u
cookie1 := &http.Cookie{Name: "sample", Value: "sample", HttpOnly: false}
http.SetCookie(w, cookie1)
Below shows how we use cookie in our product:
func handleFoo(w http.ResponseWriter, r *http.Request) {
// cookie will get expired after 1 year
expires := time.Now().AddDate(1, 0, 0)
ck := http.Cookie{
Name: "JSESSION_ID",
Domain: "foo.com",
Path: "/",
Expires: expires,
}
// value of cookie
ck.Value = "value of this awesome cookie"
// write the cookie to response
http.SetCookie(w, &ck)
// ...
}
It was not working for me in Safari until I added the Path and MaxAge. Both secure and regular cookies worked for me
Sharing so that it helps someone who is stuck like me for more than 2 days :)
expire := time.Now().Add(20 * time.Minute) // Expires in 20 minutes
cookie := http.Cookie{Name: "username", Value: "nonsecureuser", Path: "/", Expires: expire, MaxAge: 86400}
http.SetCookie(w, &cookie)
cookie = http.Cookie{Name: "secureusername", Value: "secureuser", Path: "/", Expires: expire, MaxAge: 86400, HttpOnly: true, Secure: true}
http.SetCookie(w, &cookie)
First, you need to create Cookie and then using http package's SetCookie() function you can set the cookie.
expire := time.Now().Add(10 * time.Minute)
cookie := http.Cookie{Name: "User", Value: "John", Path: "/", Expires: expire, MaxAge: 90000}
http.SetCookie(w, &cookie)
You can use gorilla package for handling cookies or i would say secure cookies: http://www.gorillatoolkit.org/pkg/securecookie
참고URL : https://stackoverflow.com/questions/12130582/setting-cookies-with-net-http
'program tip' 카테고리의 다른 글
빌드 중 면도기 오류 확인 (0) | 2020.11.18 |
---|---|
멀티 뷰 애플리케이션을위한 knockoutjs 패턴의 예 (0) | 2020.11.18 |
jasmine으로 단위 테스트를 할 때 AngularJS에서 서비스를 어떻게 모의합니까? (0) | 2020.11.18 |
SQL 바꾸기 함수 내부의 정규식 패턴? (0) | 2020.11.18 |
무한 루프는 컴파일 오류없이 메서드 서명을 중단합니다. (0) | 2020.11.18 |