更改引用标志的if语句内的变量的值

时间:2018-03-16 21:30:39

标签: go mux gorilla

我有以下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路由器和CombinedLoggingHandlerCompressHandler上使用标记?

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())
}

1 个答案:

答案 0 :(得分:2)

您似乎正在尝试将中间件添加到您的gorilla / mux路由器。

您可以使用Router.Use()添加中间件。

Router.Use()需要mux.MiddlewareFunc,这只是一个带有签名func (http.Handler) http.Handler的函数。您将遇到的大多数中间件都匹配此签名,或者可以轻松地将其包装起来,如下例所示。

从我自己的一些内部代码中删除:

func myLoggingHandler(next http.Handler) http.Handler {
    return handlers.CombinedLoggingHandler(os.Stdout, next)
}

func main() {
    r := mux.NewRouter()

    if logging {
        r.Use(myLoggingHandler)
    }
    if compress {
        r.Use(handlers.CompressHandler)
    }

    http.Handle("/", r)

    log.Fatal(http.ListenAndServe("[::]:8009", nil))

}