我正在为go寻找一个快速的框架,我偶然发现了https://github.com/valyala/fasthttp,据开发人员说,这个基准比Golang /http包快10倍。我已经很熟悉大猩猩工具包和其他基于网络/http的框架,比如gonic、goji和gocraft。
我的问题是:是否可以将net/http框架/工具包与fasthttp混合使用,例如,我想使用一些带有echo / iris的大猩猩包(框架)?
发布于 2019-08-31 16:51:41
我认为从零开始替换文件将是最好的解决方案。这里有一个示例,它显示了默认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列表,每个绑定作为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")
}发布于 2016-06-30 08:57:27
我正在检查Iris框架,我在文档中看到,可以在这个框架中使用net/http。
https://kataras.gitbooks.io/iris/content/using-native-httphandler.html
该框架使用以下方法将本机net/http处理程序转换为fasthttp处理程序。
https://github.com/valyala/fasthttp/tree/master/fasthttpadaptor
https://stackoverflow.com/questions/38094739
复制相似问题