未使用Golang设置Cookie

时间:2018-09-13 10:55:36

标签: go cookies

我有一个用于登录用户的REST API,该API在浏览器上为已登录的用户设置了cookie,并且其运行良好。 问题是,当用户从注册API完成注册后,我想调用登录​​API时,一切正常,但cookie并未设置为浏览器。

这是登录API:

var loginViaDjangoApiShim = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

        var t loginPost
        var oldCookieToken string

        decoder := json.NewDecoder(r.Body)
        _:= decoder.Decode(&t)
        expiration := time.Now().Add(365 * 24 * time.Hour)

        flagToReturn, cookie, _:= postToApiShim(t.Username, t.Password)
        if flagToReturn == "pass" {
            CookieToken = generateOldCookie(authIdFromUserName.ID)

            newCookieToSet := http.Cookie{Name: "ddagyeog", Value: CookieToken , Expires: expiration, Domain: COOKIE_DOMAIN, Path: "/", Secure: false, HttpOnly: true}
            http.SetCookie(w, &newCookieToSet)
        }
        returnValues := returnLoginFlag{Flag: flagToReturn, Cookie: ""}
        json.NewEncoder(w).Encode(returnValues)

    })

这里是注册API:

var signUpStart = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

    var t StartFlowPost

    decoder := json.NewDecoder(r.Body)
    _:= decoder.Decode(&t)
        insertIntoUser := InsertMethod(t)
            flag, _ := loginOnCoppaAndNonCoppaUsersSignup(t.UserName, t.Password)

        log.Println(flag)
        json.NewEncoder(w).Encode(flag)

})

下面是loginOnCoppaAndNonCoppaUsersSignup,它在注册用户后调用登录API。

func loginOnCoppaAndNonCoppaUsersSignup(userName, password string) (flag returnSignUpFlagCoppa, err error) {
    var loginFlag returnLoginFlag
    var jsonStr = []byte(`{
    "username":"` + userName + `",
    "password":"` + password + `"
    }`)

    request, _ := http.NewRequest("POST", USER_ROOT_URL+"login", bytes.NewBuffer(jsonStr))
    request.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    response, _:= client.Do(request)

    decoder := json.NewDecoder(response.Body)
    if err = decoder.Decode(&loginFlag); err != nil {
        return flag, err
    }

    if loginFlag.Flag == "pass" {
        flag = returnSignUpFlagCoppa{Flag: "pass", Username: userName}
        log.Println(flag)
    } else {
        flag := returnSignUpFlagCoppa{Flag: "error"}
        log.Println(flag)
    }

    return flag, nil
}

1 个答案:

答案 0 :(得分:1)

在这里您可以从登录URL响应之类获取cookie。

cookies := response.Cookies()

然后,您必须在注册API中再次使用http.SetCookie()设置这些cookie。请遵循以下代码。

for _, cookie := range response.Cookies() {
    http.SetCookie(w, cookie)
 }