Как читать куки с Голанга? - PullRequest
0 голосов
/ 20 января 2019

Я установил cookie из javascript, например:

setCookie("appointment", JSON.stringify({
                appointmentDate: selectedDay.date,
                appointmentStartMn: appointment.mnRange[0],
                appointmentId: appointment.id || 0,
                appointmentUserId: appointment.user.id || 0
          })
);

После установки cookie я хочу перенаправить пользователя на страницу бронирования:

window.location.href = "https://localhost:8080/booking/"

Функция setCookie:

function setCookie(cookieName, cookieValue) {
    document.cookie = `${cookieName}=${cookieValue};secure;`;
}

Я бы хотел получить этот cookie из моего внутреннего интерфейса, но не могу понять, как это сделать. Я читал об этом вопросе, так как никогда раньше не использовал куки, но ответы, похоже, говорят о том, что мне не нужно ничего делать, кроме настройки document.cookie.

В моем браузере я вижу, что cookie действительно установлен так, как ожидалось.

В моем бэкэнде я хочу напечатать cookie:

r.HandleFunc("/booking/", handler.serveTemplate)

func (handler *templateHandler) serveTemplate(w http.ResponseWriter, r *http.Request) {
    c, err := r.Cookie("appointment")
    if err != nil {
        fmt.Println(err.Error())
    } else {
        fmt.Println(c.Value)
    }
}

//output http: named cookie not present

Что конкретно мне не хватает? Я думаю, что запутываю локальные / http cookie, но как добиться чтения файлов cookie, установленных клиентом?

ОБНОВЛЕНИЕ (подробнее см. Ответ)

Это не имеет ничего общего с Голангом. Мой:

appointmentDate: selectedDay.date

То, что отформатировано как 2019-01-01 и -, не является допустимым символом, который можно отправить на сервер. Он работал в моем браузере, но для его передачи необходимо закодировать URI.

Вот так и вышло:

`${cookieName}=${encodeURIComponent(cookieValue)};secure;` + "path=/";`

И на ходу (не поймал здесь ошибку, чтобы сэкономить место):

cookie, _ := r.Cookie("appointment")
data, _ := url.QueryUnescape(cookie.Value)

1 Ответ

0 голосов
/ 20 января 2019

Лучшим способом было бы, например, кодировать ваш json в base64. Я сделал рабочий пример ...

main.go

package main

import (
    "encoding/base64"
    "encoding/json"
    "fmt"
    "io"
    "io/ioutil"
    "net/http"
)

// Contains everything about an appointment
type Appointment struct {
    Date    string `json:"appointmentDate"`    // Contains date as string
    StartMn string `json:"appointmentStartMn"` // Our startMn ?
    ID      int    `json:"appointmentId"`      // AppointmentId
    UserID  int    `json:"appointmentUserId"`  // UserId
}

func main() {
    handler := http.NewServeMux()

    // Main request
    handler.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Printf("Requested /\r\n")

        // set typical headers
        w.Header().Set("Content-Type", "text/html")
        w.WriteHeader(http.StatusOK)

        // Read file
        b, _ := ioutil.ReadFile("index.html")
        io.WriteString(w, string(b))
    })

    // booking request
    handler.HandleFunc("/booking/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Printf("Requested /booking/\r\n")

        // set typical headers
        w.Header().Set("Content-Type", "text/html")
        w.WriteHeader(http.StatusOK)

        // Read cookie
        cookie, err := r.Cookie("appointment")
        if err != nil {
            fmt.Printf("Cant find cookie :/\r\n")
            return
        }

        fmt.Printf("%s=%s\r\n", cookie.Name, cookie.Value)

        // Cookie data
        data, err := base64.StdEncoding.DecodeString(cookie.Value)
        if err != nil {
            fmt.Printf("Error:", err)
        }

        var appointment Appointment
        er := json.Unmarshal(data, &appointment)
        if err != nil {
            fmt.Printf("Error: ", er)
        }

        fmt.Printf("%s, %s, %d, %d\r\n", appointment.Date, appointment.StartMn, appointment.ID, appointment.UserID)

        // Read file
        b, _ := ioutil.ReadFile("booking.html")
        io.WriteString(w, string(b))
    })

    // Serve :)
    http.ListenAndServe(":8080", handler)
}

index.html

<html>
    <head>
        <title>Your page</title>
    </head>
<body>
    Setting cookie via Javascript

    <script type="text/javascript">
    window.onload = () => {
        function setCookie(name, value, days) {
            var expires = "";
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days*24*60*60*1000));
                expires = "; expires=" + date.toUTCString();
            }
            document.cookie = name + "=" + btoa((value || ""))  + expires + "; path=/";
        }

        setCookie("appointment", JSON.stringify({
                    appointmentDate: "20-01-2019 13:06",
                    appointmentStartMn: "1-2",
                    appointmentId: 2,
                    appointmentUserId: 3
            })
        );

        document.location = "/booking/";
    }
    </script>
</body>

booking.html

<html>
    <head>
        <title>Your page</title>
    </head>
<body>
    Your booking is okay :)
</body>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...