GolangNote

Golang笔记

goji + Context 例子

Permalink

goji + Context 例子

context.go 中间件

Go: middleware
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// framework/middleware/context.go
package middleware
 
import (
    "net/http"
 
    "github.com/zenazn/goji/web"
    "golang.org/x/net/context"
)
 
// ContextKey is key name for stored context
const ContextKey = "context"
 
// Context creates new Context for new request
func Context(c *web.C, h http.Handler) http.Handler {
    fn := func(w http.ResponseWriter, r *http.Request) {
        ctx := context.Background()
        ctx = context.WithValue(ctx, "request", r)
        c.Env[ContextKey] = ctx
        h.ServeHTTP(w, r)
    }
    return http.HandlerFunc(fn)
}

主程序

Go: main.go
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
// main.go
package main
 
import (
    "flag"
 
    "github.com/zenazn/goji"
    "github.com/zenazn/goji/web"
    "github.com/zenazn/goji/web/middleware"
 
    mw "github.com/eure/example-blog-golang/framework/middleware" // <- set alias to avoid name conflict
    "github.com/eure/example-blog-golang/routing"
)
 
func main() {
    flag.Set("bind", ":1234")
 
    // api v1 routing
    routeV1 := web.New()
    routeV1.Use(mw.Context) // <- create context
    routeV1.Use(middleware.SubRouter)
    goji.Handle("/api/v1/*", routeV1)
    routing.SetV1(routeV1)
 
    // run http server
    goji.Serve()
}

context 已保存在 c.Env["context"],建立一个 controller/context.go 文件

Go: context.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// controller/context.go
package controller
 
import (
    "github.com/zenazn/goji/web"
    "golang.org/x/net/context"
 
    "github.com/eure/example-blog-golang/framework/middleware"
)
 
// GetContext returns context
func GetContext(c web.C) context.Context {
    if ctx, ok := c.Env[middleware.ContextKey]; ok {
        return ctx.(context.Context)
    }
    panic("context missing!!")
}

然后可以这么使用:

Go: author_controller.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// controller/apiv1/author_controller.go
 
func GetAuthor(c web.C, w http.ResponseWriter, r *http.Request) {
    data := controller.NewResponse()
    data.Add("object", "author")
    data.Add("name", c.URLParams["name"])
 
    ctx := controller.GetContext(c)
    if ctx != nil {
        r2 := ctx.Value("request").(*http.Request)
        data.Add("is_same_request", r == r2)
    }
    controller.RenderJSON(w, data)
}

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

Related articles

goji v2 与goji 的对接

goji 是个优秀的框架,作者说以前是弄着玩的,后来较正规的按照go 的设计原则来重构,不过尽量保持原来的接口。...

关掉goji 的log 输出

goji 默认对每个请求都输出请求时间,在项目刚起步时可以作为性能参考,但在实际生产环境里,可以关掉log...

Write a Comment to "goji + Context 例子"

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