我一直在寻找一个快速的 go 框架,我偶然发现了 fasthttp https://github.com/valyala/fasthttp根据开发人员的说法,基准测试比 Golang net/http 包快 10 倍。我已经熟悉 gorilla 工具包和其他基于 net/http 的框架,例如 gin-gonic、goji 和 gocraft。
我的问题是:是否可以将 net/http 框架/工具包与 fasthttp 混合使用,例如我想使用一些带有 echo/iris(fasthttp 框架)的 gorilla 包?
最佳答案
我认为从头文件替换将是最好的解决方案。这是一个显示默认 net/http 和 fasthttp 之间差异的示例
设置 net/http 默认包的示例。 基本的低效方法
/* Global var */
var logcfg = initConfigurationData("test/")
var fileList = initLogFileData(logcfg)
func main() {
channel := make(chan bool)
/* Run coreEngine in background, parameter not necessary */
go coreEngine(fileList, logcfg, channel)
log.Println("Started!")
handleRequests()
<-channel
log.Println("Finished!")
}
之后,您可以声明一个包含所有“API”的“包装器”,如以下“handleRequest”方法
func handleRequests() {
// Map the endoint to the function
http.HandleFunc("/", homePage)
http.HandleFunc("/listAllFile", listAllFilesHTTP)
http.HandleFunc("/getFile", getFileHTTP)
log.Fatal(http.ListenAndServe(":8081", nil))
}
这是 API 列表,每个 API 都绑定(bind)为 HandleFunc 的第一个参数,并使用方法提供的核心功能进行管理(示例):
// Example of function for print a list of file
func listAllFilesHTTP(w http.ResponseWriter, r *http.Request) {
tmp := make([]string, len(fileList))
for i := 0; i < len(fileList); i++ {
tmp[i] = fileList[i].name
}
fmt.Fprintf(w, strings.Join(tmp, "\n"))
log.Println("Endpoint Hit: listFile")
}
从另一方面来说,使用 fasthttp,您必须如下更改 handleRequest 方法
func handleRequests() {
m := func(ctx *fasthttp.RequestCtx) {
switch string(ctx.Path()) {
case "/":
fastHomePage(ctx)
case "/listAllFile":
fastListAllFilesHTTP(ctx)
case "/getFile":
fastGetFileHTTP(ctx)
default:
ctx.Error("not found", fasthttp.StatusNotFound)
}
}
fasthttp.ListenAndServe(":8081", m)
}
然后,核心函数如下:
注意:您也可以将上下文中的其他变量传递给方法。
// NOTE: The signature have changed!
func fastListAllFilesHTTP(ctx *fasthttp.RequestCtx) {
ctx.Response.Header.Set("GoLog-Viewer", "v0.1$/alpha")
tmp := make([]string, len(fileList))
for i := 0; i < len(fileList); i++ {
tmp[i] = fileList[i].name
}
fmt.Fprintf(ctx, strings.Join(tmp, "\n"))
log.Println("Endpoint Hit: listFile")
}
关于go - 结合 net/http 和 fasthttp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38094739/