英文:
go > how to refactor http handler from main
问题
我正在学习Go语言,但还有一些知识欠缺。我正在编写一个HTTP静态服务器(第一阶段是为了提供资源)。同时,我也尝试使用gorilla/mux包作为路由器。
到目前为止,我得到了以下代码:
package 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)
这是一个相当基本的问题,我想学习如何编写更好看的代码。
你能给予一些建议吗?谢谢。
英文:
I'm learning go language and I still have some lack of knowledge. I'm writing http static server (in 1st phase to serve assets). Also I'm trying to use gorilla/mux package as router.
So far I ended up with
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)
}
it works fine and serves all files under /public/
Now I'd like to refactor code
r.PathPrefix("/public/").Handler(http.StripPrefix("/public/",
http.FileServer(http.Dir("public/"))))
to be in form
r.PathPrefix("/public/").Handler(PublicHandler)
It's quite basic and I'd like to learn how to make better looking code.
Can you advice on this? Thx.
答案1
得分: 1
只需将处理程序分配给一个变量:
PublicHandler := http.StripPrefix("/public/", http.FileServer(http.Dir("public/")))
r.PathPrefix("/public/").Handler(PublicHandler)
英文:
Simply assign the handler to a variable:
PublicHandler := http.StripPrefix("/public/", http.FileServer(http.Dir("public/")))
r.PathPrefix("/public/").Handler(PublicHandler)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论