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 转摘请注明来源