GolangNote

Golang笔记

goji v2 与goji 的对接

Permalink

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

下面是正式版的一点改变:

Diff: goji v2 & v1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Getting objects from the request context
- c.Env["key"]
+ ctx.Value("key")

// Setting objects
- c.Env["key"] = someVal
+ ctx = context.WithValue(ctx, "key", someVal)

// Route parameters
- c.URLParams["name"]
+ pat.Param(ctx, "name")

// Creating multiplexers (muxes/routers)
- web.New()
+ goji.NewMux()

// Routes and handlers
- mux.Get("/route", YourHandler)
+ mux.HandleC(pat.Get("/route"), YourHandler) // Use mux.Handle for vanilla http.Handler

sample 的改变

Go: goji v2 sample
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package main

import (
        "fmt"
        "net/http"

        "goji.io"
        "goji.io/pat"
        "golang.org/x/net/context"
)

func hello(ctx context.Context, w http.ResponseWriter, r *http.Request) {
        name := pat.Param(ctx, "name")
        fmt.Fprintf(w, "Hello, %s!", name)
}

func main() {
        mux := goji.NewMux()
        mux.HandleFuncC(pat.Get("/hello/:name"), hello)

        http.ListenAndServe("localhost:8000", mux)
}

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

Related articles

Write a Comment to "goji v2 与goji 的对接"

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