【发布时间】:2018-08-26 01:19:38
【问题描述】:
我有以下 Go 程序,它是一个静态文件服务器。我在控制台中收到以下错误:
..\static\main.go:45:5: cannot use handlers.CombinedLoggingHandler(os.Stdout, r) (type http.Handler) as type *mux.Router in assignment: need type assertion
..\static\main.go:52:5: cannot use handlers.CompressHandler(l) (type http.Handler) as type *mux.Router in assignment: need type assertion
如何在 Gorilla Mux 路由器和 CombinedLoggingHandler 或 CompressHandler 中使用标志?
package main
import (
"flag"
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
controllers "<this_is_a_local_repo>"
common "<this_is_a_local_repo>"
)
var (
host = flag.String("host", "127.0.0.1", "TCP host to listen to")
port = flag.String("port", "8081", "TCP port to listen to")
logging = flag.Bool("logging", false, "Whether to enable HTTP response logging")
compress = flag.Bool("compress", true, "Whether to enable transparent response compression")
dir = flag.String("dir", common.Abs("public"), "Directory to serve static files from")
)
func main() {
flag.Parse()
r := mux.NewRouter().StrictSlash(true)
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(*dir))))
r.PathPrefix("/").HandlerFunc(controllers.IndexHandler(*dir + "/index.html")) // catch-all route for 404
l := r
if *logging {
l = handlers.CombinedLoggingHandler(os.Stdout, r)
}
h := l
if *compress {
h = handlers.CompressHandler(l) // gzip all responses
}
srv := &http.Server{
Handler: h,
Addr: fmt.Sprintf("%s:%s", *host, *port),
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 15 * time.Second,
}
log.Fatal(srv.ListenAndServe())
}
【问题讨论】:
-
var h http.Handler = r,如果 ... 那么h = handlers.CombinedLoggingHandler(os.Stdout, h),如果 ... 那么h = handlers.CompressHandler(h)。不用l := r和h := l,做h = middleware(h)就可以了。 -
您正在为
CombinedLoggingHandler和CompressHandler分配一个*路由器。它们都需要处理程序类型,但这里不是这种情况 -
@Himanshu 你的意思是 return 对吗?因为只要他们将
http.Handler作为参数,代码就可以了,因为*mux.Router实现了该接口。问题是他们也 return 一个http.Handler但赋值左侧的值的类型是*mux.Router而不是http.Handler...问题是什么类型这两个函数return,而不是它们需要的参数。 -
根据第一条评论,他应该修复它play.golang.org/p/zD5Ran7t3Kj
-
@mkopriva
http.Handler是一个使用servemux作为接收者的函数。您已经声明了该类型的变量。汉德是一种类型?我从未见过声明函数类型的变量。请详细说明。我正处于学习阶段