如何从主函数中重构HTTP处理程序?

huangapple go评论81阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2014年5月8日 20:58:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/23542466.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定