Golang http mux更改处理程序函数
我是一个新手,还没有找到任何关于这方面的信息,也许这在这个时候是不可能的 我正在尝试删除或替换mux路由(使用http.NewServeMux或gorilla的mux.Router)。我的最终目标是能够启用/禁用一个或多个路由,而无需重新启动程序 我可能可以在处理程序对处理程序的基础上完成这项工作,如果该功能被“禁用”,则只返回404,但我更愿意找到一种更通用的方法来完成这项工作,因为我希望为应用程序中的每个路由实现它 或者我最好只跟踪禁用的url模式,并使用一些中间件来防止处理程序执行Golang http mux更改处理程序函数,go,gorilla,Go,Gorilla,我是一个新手,还没有找到任何关于这方面的信息,也许这在这个时候是不可能的 我正在尝试删除或替换mux路由(使用http.NewServeMux或gorilla的mux.Router)。我的最终目标是能够启用/禁用一个或多个路由,而无需重新启动程序 我可能可以在处理程序对处理程序的基础上完成这项工作,如果该功能被“禁用”,则只返回404,但我更愿意找到一种更通用的方法来完成这项工作,因为我希望为应用程序中的每个路由实现它 或者我最好只跟踪禁用的url模式,并使用一些中间件来防止处理程序执行 如果有
如果有人至少能给我指出正确的方向,我绝对会发布解决方案的代码示例,假设有。谢谢 没有内置的方法,但很容易实现 是的,你可以 一种方法是使用sturct实现方法的
http.Handle
接口
ServeHTTP
。
然后让结构包含另一个类似gorilla的muxer
最后有一个原子开关来启用/禁用子例程
这是我的意思的一个工作示例:
package main
import (
"fmt"
"github.com/gorilla/mux"
"net/http"
"sync/atomic"
)
var recording int32
func isRecording() bool {
return atomic.LoadInt32(&recording) != 0
}
func setRecording(shouldRecord bool) {
if shouldRecord {
atomic.StoreInt32(&recording, 1)
} else {
atomic.StoreInt32(&recording, 0)
}
}
type SwitchHandler struct {
mux http.Handler
}
func (s *SwitchHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if isRecording() {
fmt.Printf("Switch Handler is Recording\n")
s.mux.ServeHTTP(w, r)
return
}
fmt.Printf("Switch Handler is NOT Recording\n")
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, "NOT Recording\n")
}
func main() {
router := mux.NewRouter()
router.HandleFunc("/success/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Recording\n")
})
handler := &SwitchHandler{mux: router}
setRecording(false)
http.Handle("/", handler)
http.ListenAndServe(":8080", nil)
}
根据协议,建议交换路由器,而不是删除路由。现有连接将保持打开状态
package main
import (
"fmt"
"github.com/gorilla/mux"
"net/http"
"sync/atomic"
)
var recording int32
func isRecording() bool {
return atomic.LoadInt32(&recording) != 0
}
func setRecording(shouldRecord bool) {
if shouldRecord {
atomic.StoreInt32(&recording, 1)
} else {
atomic.StoreInt32(&recording, 0)
}
}
type SwitchHandler struct {
mux http.Handler
}
func (s *SwitchHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if isRecording() {
fmt.Printf("Switch Handler is Recording\n")
s.mux.ServeHTTP(w, r)
return
}
fmt.Printf("Switch Handler is NOT Recording\n")
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, "NOT Recording\n")
}
func main() {
router := mux.NewRouter()
router.HandleFunc("/success/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Recording\n")
})
handler := &SwitchHandler{mux: router}
setRecording(false)
http.Handle("/", handler)
http.ListenAndServe(":8080", nil)
}