youbbs avatar

muxie:一个新兴的兼容net/http 快速路由

🕐 by youbbs

muxie 是个简单、快速、轻便的路由,其作者在两年多前开发的颇有争议的基于fasthttp 框架 iris。前不久开源出这个路由库,很赞的是100%兼容net/http。

muxie hello world

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
28
29
30
31
32
33
34
35
36
package main

import (
	"fmt"
	"net/http"

	"github.com/kataras/muxie"
)

func main() {
	mux := muxie.NewMux()

	// if it is true the /about/ will be permantly redirected to /about and served from the aboutHandler.
	// mux.PathCorrection = true

	mux.HandleFunc("/", indexHandler)
	mux.HandleFunc("/index", indexHandler)
	mux.HandleFunc("/about", aboutHandler)

	fmt.Println(`Server started at http://localhost:8080
Open your browser or any other HTTP Client and navigate to:
http://localhost:8080
http://localhost:8080/index and
http://localhost:8080/about`)

	http.ListenAndServe(":8080", mux)
}

func indexHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html;charset=utf8")
	fmt.Fprintf(w, "This is the <strong>%s</strong>", "index page")
}

func aboutHandler(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("Simple example to show how easy is to add routes with static paths.\nVisit the 'parameterized' example folder for more...\n"))
}

muxie 路由风格跟goji 类似,当年比较喜欢goji 是因为其开发者比较成熟,不参与各种路由性能竞赛,以稳定和兼容为主。

goji hello world

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

import (
	"fmt"
	"net/http"

	"goji.io"
	"goji.io/pat"
)

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

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

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

参考:

💘 相关文章

写一条评论

Based on Golang + fastHTTP + sdb | go1.16.3 Processed in 1ms