GolangNote

Golang笔记

Goji 使用session 的示例,可以引申全局的数据连接

Permalink

Goji 使用session 的示例,可以引申全局的数据连接。

Goji 使用session

Go: Goji 使用session
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package main

import (
    "fmt"
    "log"
    "net/http"
    "os"

    "github.com/zenazn/goji"
    "github.com/zenazn/goji/web"
)

type Controller struct {
    session *Session
}

func NewController() (*Controller, error) {
    if uri := os.Getenv("MONGOHQ_URL"); uri == "" {
        return nil, fmt.Errorf("no DB connection string provided")
    }
    session, err := mgo.Dial(uri)
    if err != nil {
        return nil, err
    }
    return &Controller{
        session: session,
    }, nil
}

func (c *Controller) getUser(c web.C, w http.ResponseWriter, r *http.Request) {
    // Use the session var here
}

func main() {
    ctl, err := NewController()
    if err != nil {
        log.Fatal(err)
    }
    defer ctl.session.Close()

    goji.Get("/user", ctl.getUser)
    goji.Serve()
}

本文网址: https://golangnote.com/topic/63.html 转摘请注明来源

Related articles

Golang Web 程序生产环境独立部署示例

一个 web 应用通常是跑在一个前端代理,如 Nginx 后,这样可以方便的在同一个服务器部署多个应用。这里说的独立部署是指让 go web 程序直接暴露在外面,独占 443、80 端口(俗称裸跑)。这样做除了性能有些提高外,更重要的是部署方便。...

Write a Comment to "Goji 使用session 的示例,可以引申全局的数据连接"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 0ms