1 回答

TA貢獻1831條經驗 獲得超4個贊
當您的處理程序需要一個變量時,通常意味著您應該實現Handler接口而不是提供HandlerFunc函數。
這是一個不好的例子(使用全局變量):
var globalThing string
func specificHandler(w http.ResponseWriter, r *http.Request) {
w.Write(globalConfigThing)
}
func main() {
globalThing = "Hello world!"
http.HandleFunc("/something", specificHandler)
http.ListenAndServe(":8080", nil)
}
這是一個更好的例子(不使用全局變量):
type specificHandler struct {
Thing string
}
func (h *specificHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Write(h.Thing)
}
func main() {
http.Handle("/something", &specificHandler{Thing: "Hello world!"})
http.ListenAndServe(":8080", nil)
}
如您所見,aHandler可以封裝變量。
為了完整性,另一種方法是使用函數閉包。這適用于一次性處理程序,但不可重用,并且更難為其編寫單元測試。
func main() {
scopedThing := "Hello world!"
http.HandleFunc("/something", func (w http.ResponseWriter, r *http.Request) {
w.Write(scopedThing)
})
http.ListenAndServe(":8080", nil)
}
正確完成后,您現在可以somepackage通過將全局變量作為參數等傳遞來避免包中的全局變量。
編輯:例如,您可以使用包中的幾個PriorityQueueAStar字段定義處理程序結構somepackage:
type specificHandler struct {
QueueA somepackage.PriorityQueueAStar
QueueB somepackage.PriorityQueueAStar
QueueC somepackage.PriorityQueueAStar
}
func (h *specificHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.QueueA.Push(h.QueueB.Pop)
h.QueueB.Push(h.QueueC.Pop)
w.Write([]byte("Queues pushed and popped"))
}
- 1 回答
- 0 關注
- 223 瀏覽
添加回答
舉報