-2

我正在学习围棋语言,但我仍然缺乏一些知识。我正在编写 http 静态服务器(在第一阶段服务资产)。另外我正在尝试使用 gorilla/mux 包作为路由器。

到目前为止,我结束了

pagekage main

import (
    "fmt"
    "github.com/gorilla/mux"
    "html"
    "net/http"
)

func HomeHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
}

func main() {

    r := mux.NewRouter()
    r.HandleFunc("/", HomeHandler)
    r.PathPrefix("/public/").Handler(http.StripPrefix("/public/",
        http.FileServer(http.Dir("public/"))))

    http.Handle("/", r)
    http.ListenAndServe(":8080", nil)

}

它工作正常并提供 /public/ 下的所有文件

现在我想重构代码

r.PathPrefix("/public/").Handler(http.StripPrefix("/public/",
            http.FileServer(http.Dir("public/"))))

在形式

r.PathPrefix("/public/").Handler(PublicHandler)

这是非常基本的,我想学习如何制作更好看的代码。

你能就此提出建议吗?谢谢。

4

1 回答 1

1

只需将处理程序分配给一个变量:

PublicHandler := http.StripPrefix("/public/", http.FileServer(http.Dir("public/")))
r.PathPrefix("/public/").Handler(PublicHandler)
于 2014-05-08T13:09:56.800 回答