1
0

flash.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Copyright (C) 2019-2022 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. package httpd
  15. import (
  16. "encoding/base64"
  17. "net/http"
  18. "time"
  19. )
  20. const (
  21. flashCookieName = "message"
  22. )
  23. func setFlashMessage(w http.ResponseWriter, r *http.Request, value string) {
  24. http.SetCookie(w, &http.Cookie{
  25. Name: flashCookieName,
  26. Value: base64.URLEncoding.EncodeToString([]byte(value)),
  27. Path: "/",
  28. Expires: time.Now().Add(60 * time.Second),
  29. MaxAge: 60,
  30. HttpOnly: true,
  31. Secure: isTLS(r),
  32. SameSite: http.SameSiteLaxMode,
  33. })
  34. }
  35. func getFlashMessage(w http.ResponseWriter, r *http.Request) string {
  36. cookie, err := r.Cookie(flashCookieName)
  37. if err != nil {
  38. return ""
  39. }
  40. http.SetCookie(w, &http.Cookie{
  41. Name: flashCookieName,
  42. Value: "",
  43. Path: "/",
  44. Expires: time.Unix(0, 0),
  45. MaxAge: -1,
  46. HttpOnly: true,
  47. Secure: isTLS(r),
  48. SameSite: http.SameSiteLaxMode,
  49. })
  50. message, err := base64.URLEncoding.DecodeString(cookie.Value)
  51. if err != nil {
  52. return ""
  53. }
  54. return string(message)
  55. }