我不确定为什么我的路线不匹配。 匹配,我得到预期的输出,但不是。当我尝试在浏览器上进行匹配时,我得到了。localhost:8000localhost:8000/admin/test404/admin/test
我想以这种方式组织我的代码,因为我想在每个.package
项目结构
/admin
admin.go
main.go
main.go
package main
import (
"example.com/liondancer/playground/admin"
"fmt"
"github.com/gorilla/mux"
"log"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hi there!")
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/", handler)
r.PathPrefix("/admin").Handler(admin.NewHandler())
log.Fatal(http.ListenAndServe(":8000", r))
}
admin.go
package admin
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
)
type Handler struct {
router *mux.Router
}
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.router.ServeHTTP(w, r)
}
func NewHandler() *Handler {
h := &Handler{}
r := mux.NewRouter()
h.router = r
h.addRoutes()
return h
}
func (h *Handler) addRoutes() {
fmt.Print("hi here"). // <--- printed here to prove func gets ran.
h.router.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "test")
})
}
手掌心
拉风的咖菲猫
相关分类