Hugo.Huang
Hugo.Huang

Reputation: 1

How to get cookie and session outside of controller in beego

I wanna get and set cookie in my service file, but the code "ctx.SetCookie()" always get error "invalid memory address or nil pointer dereference", please help me, thanks in advance

I have tried two methods to deal this problem,but there is still something wrong with it

method 1:

type security struct {
    beego.Controller
}
...
func (s security) CheckToken(){
    ...

    ctx.SetCookie("token","xxxxxxxx")
}

methos 2:

import "github.com/astaxie/beego/context"

func (s security) CheckToken(){
    ...
    ctx := context.NewContext()
    ctx.SetCookie("token","xxxxxxxx")
}

panic: runtime error: invalid memory address or nil pointer dereference [signal SIGSEGV: segmentation violation code=0x1 addr=0x10 pc=0x832639]

Upvotes: 0

Views: 1251

Answers (2)

ahmetlutfu
ahmetlutfu

Reputation: 325

You can set via beego filter.

var SetCookie = func(ctx *context.Context) {
    ctx.SetCookie("token", "xxxxxxxx")
}

beego.InsertFilter("/*", beego.BeforeRouter, SetCookie)

Upvotes: 1

novalagung
novalagung

Reputation: 11532

Set cookie can be done via .SetCookie() method of beego context object. The context object itself is accessible via any controller that embed beego.Controller.

func (c *MainController) SetToken() {
    c.Ctx.SetCookie("token", "xxxxxxxx")
}

func (c *MainController) GetToken() {
    cookieValue := c.Ctx.GetCookie("token")
    fmt.Println(cookieValue)
}

Doc https://beego.me/docs/module/context.md

Update #1

I wanna to set cookie outside of controller

What you need to do is pass the context object of the controller into the particular function. For example:

package models

import "github.com/astaxie/beego/context"

func SetCookieFromHere(ctx *context.Context) {
    ctx.SetCookie("token", "xxxxxxxx")
}
package controllers

import "yourpackage/models"

func (c *MainController) SetToken() {
    models.SetCookieFromHere(c.Ctx)
}

Upvotes: 1

Related Questions