gpt4 book ai didi

http - 用net/http构建子路由器的好方法

转载 作者:行者123 更新时间:2023-12-01 22:15:05 24 4
gpt4 key购买 nike

我正在构建一个使用net/http处理多个路径的API服务器。我想将其构建为子路由器,但是我不知道这样做的好方法。

现在,我在想如下。

package main

import (
"database/sql"
"log"
"net/http"
)

type Config struct {
db *sql.DB
}

type UserRouter struct {
mux *http.ServeMux
cfg *Config
}

func (u *UserRouter) Create(w http.ResponseWriter, r *http.Request) {
// process handler logic
w.Write([]byte("Create"))
}

func (u *UserRouter) Delete(w http.ResponseWriter, r *http.Request) {
// process handler logic
w.Write([]byte("Delete"))
}

// NewUserRouter is subrouter.
func NewUserRouter(cfg *Config) *UserRouter {
mux := http.NewServeMux()
u := &UserRouter{
mux: mux,
cfg: cfg,
}
mux.HandleFunc("/user/create", u.Create)
mux.HandleFunc("/user/delete", u.Delete)
return u
}

func (u *UserRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
u.mux.ServeHTTP(w, r)
}

func main() {
mux := http.NewServeMux()
cfg := &Config{nil /* Describes settings such as PostgreSQL. */}
mux.Handle("/user/", NewUserRouter(cfg))
if err := http.ListenAndServe(":8080", mux); err != nil {
log.Fatal(err)
}
}

上面的实现似乎有点多余。但是,如果子路由器路径设置如下,HTTP服务器将无法正常工作。我认为这是因为传递给ListenAndServe的多路复用器与子路由器的多路复用器不同。
// NewUserRouter is subrouter.
func NewUserRouter(cfg *Config) *UserRouter {
mux := http.NewServeMux()
u := &UserRouter{
mux: mux,
cfg: cfg,
}
- mux.HandleFunc("/user/create", u.Create)
- mux.HandleFunc("/user/delete", u.Delete)
+ mux.HandleFunc("/create", u.Create)
+ mux.HandleFunc("/delete", u.Delete)
return u
}

用net / http构建一个简单的子路由器是否很困难,我是否需要使用 go-chi/chigorilla/mux这样的WAF?

最佳答案

如果您的目标是将用户处理程序的注册与其他处理程序分开,则可以执行以下操作。不需要子路由器。

type UserRouter struct {
cfg *Config

// prefix is the path prefix for the user handlers. Use this
// value to construct paths to other user handlers.
prefix string
}

// RegisterUserHandler adds the user handlers to mux using the
// specified path prefix.
func RegisterUserHandler(cfg *Config, prefix string, mux *http.ServeMux) {
u := &UserRouter{cfg: cfg, prefix: prefix}
mux.HandleFunc(prefix+"/create", u.Create)
mux.HandleFunc(prefix+"/delete", u.Delete)
}

func main() {
mux := http.NewServeMux()
cfg := &Config{nil /* Describes settings such as PostgreSQL. */}
RegisterUserHandler(cfg, "/user", mux)
log.Fatal(http.ListenAndServe(":8080", mux))
}

关于http - 用net/http构建子路由器的好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60841156/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com