# Session 支援

第六章的時候我們介紹過如何在 Go 語言中使用 session，也實現了一個 sessionManger，beego 框架基於 sessionManager 實現了方便的 session 處理功能。

## session 整合

beego 中主要有以下的全域性變數來控制 session 處理：

```go
//related to session
SessionOn            bool   // 是否開啟 session 模組，預設不開啟
SessionProvider      string // session 後端提供處理模組，預設是 sessionManager 支援的 memory

SessionName          string // 客戶端儲存的 cookies 的名稱
SessionGCMaxLifetime int64  // cookies 有效期

GlobalSessions *session.Manager //全域性 session 控制器
```

當然上面這些變數需要初始化值，也可以按照下面的程式碼來配合配置檔案以設定這些值：

```go
if ar, err := AppConfig.Bool("sessionon"); err != nil {
    SessionOn = false
} else {
    SessionOn = ar
}
if ar := AppConfig.String("sessionprovider"); ar == "" {
    SessionProvider = "memory"
} else {
    SessionProvider = ar
}
if ar := AppConfig.String("sessionname"); ar == "" {
    SessionName = "beegosessionID"
} else {
    SessionName = ar
}
if ar, err := AppConfig.Int("sessiongcmaxlifetime"); err != nil && ar != 0 {
    int64val, _ := strconv.ParseInt(strconv.Itoa(ar), 10, 64)
    SessionGCMaxLifetime = int64val
} else {
    SessionGCMaxLifetime = 3600
}
```

在 beego.Run 函式中增加如下程式碼：

```go
if SessionOn {
    GlobalSessions, _ = session.NewManager(SessionProvider, SessionName, SessionGCMaxLifetime)
    go GlobalSessions.GC()
}
```

這樣只要 SessionOn 設定為 true，那麼就會預設開啟 session 功能，獨立開一個 goroutine 來處理 session。

為了方便我們在自訂 Controller 中快速使用 session，作者在`beego.Controller`中提供了如下方法：

```go
func (c *Controller) StartSession() (sess session.Session) {
    sess = GlobalSessions.SessionStart(c.Ctx.ResponseWriter, c.Ctx.Request)
    return
}
```

## session 使用

透過上面的程式碼我們可以看到，beego 框架簡單地繼承了 session 功能，那麼在專案中如何使用呢？

首先我們需要在應用的 main 入口處開啟 session：

```go
beego.SessionOn = true
```

然後我們就可以在控制器的相應方法中如下所示的使用 session 了：

```go
func (this *MainController) Get() {
    var intcount int
    sess := this.StartSession()
    count := sess.Get("count")
    if count == nil {
        intcount = 0
    } else {
        intcount = count.(int)
    }
    intcount = intcount + 1
    sess.Set("count", intcount)
    this.Data["Username"] = "astaxie"
    this.Data["Email"] = "astaxie@gmail.com"
    this.Data["Count"] = intcount
    this.TplNames = "index.tpl"
}
```

上面的程式碼展示了如何在控制邏輯中使用 session，主要分兩個步驟：

1. 取得 session 物件

```go
    //取得物件，類似 PHP 中的 session_start()
    sess := this.StartSession()
```

1. 使用 session 進行一般的 session 值操作

```go
    //取得 session 值，類似 PHP 中的$_SESSION["count"]
    sess.Get("count")

    //設定 session 值
    sess.Set("count", intcount)
```

從上面程式碼可以看出基於 beego 框架開發的應用中使用 session 相當方便，基本上和 PHP 中呼叫`session_start()`類似。

## links

* [目錄](https://github.com/doggy8088/build-web-application-with-golang-zhtw/tree/4cbbaa31bdfc3678915eb91f23db2f1bad554a20/preface.md)
* 上一節: [靜態檔案支援](/build-web-application-with-golang-zhtw/14.0/14.1.md)
* 下一節: [表單及驗證支援](/build-web-application-with-golang-zhtw/14.0/14.3.md)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://willh.gitbook.io/build-web-application-with-golang-zhtw/14.0/14.2.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
