使用下面的代码,当我访问/ test2时,它以404响应 - 未找到./ test1正常工作.这是为什么?尽管路由器实现了http.Handler接口,但是不允许嵌套吗?
package main
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
)
func main() {
mainRouter := mux.NewRouter()
subRouter := mux.NewRouter()
mainRouter.HandleFunc("/test1", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "test1") })
subRouter.HandleFunc("/test2", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "test2") })
mainRouter.Handle("/", subRouter)
http.ListenAndServe(":9999", mainRouter)
}
Run Code Online (Sandbox Code Playgroud)
编辑:
我的主要目标是添加一些初始工作,这些工作对于subRouter中的所有路由都是常见的,并且仅适用于它们.更具体地说,我想使用Negroni作为我的中间件orchiestrator.在Negroni网站上有一个将中间件添加到路由组的示例:
router := mux.NewRouter()
adminRoutes := mux.NewRouter()
// add admin routes here
Create a new negroni for the admin middleware
router.Handle("/admin", negroni.New(
Middleware1,
Middleware2,
negroni.Wrap(adminRoutes),
))
Run Code Online (Sandbox Code Playgroud)
Negroni基本上执行每个参数的ServeHTTP方法,因为它们都实现了http.Handler.它按顺序执行它们,因此路由器路由将是最后的.
我熟悉SubrouterMux中的概念,但AFAIK我不能像上面的例子那样使用它,特别是我不能在mainRouter和它之间注入任何东西Subrouter.这就是嵌套看起来更灵活的原因.
我无法通过这种方式从会话中获得价值,它是nil:
session := initSession(r)
valWithOutType := session.Values[key]
Run Code Online (Sandbox Code Playgroud)
完整代码:
package main
import (
"fmt"
"github.com/gorilla/mux"
"github.com/gorilla/sessions"
"log"
"net/http"
)
func main() {
rtr := mux.NewRouter()
rtr.HandleFunc("/setSession", handler1).Methods("GET")
rtr.HandleFunc("/getSession", handler2).Methods("GET")
http.Handle("/", rtr)
log.Println("Listening...")
http.ListenAndServe(":3000", http.DefaultServeMux)
}
func handler1(w http.ResponseWriter, r *http.Request) {
SetSessionValue(w, r, "key", "value")
w.Write([]byte("setSession"))
}
func handler2(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("getSession"))
value := GetSessionValue(w, r, "key")
fmt.Println("value from session")
fmt.Println(value)
}
var authKey = []byte("secret") // Authorization Key
var encKey = []byte("encKey") // Encryption Key
var …Run Code Online (Sandbox Code Playgroud) 我在HTTPS(端口10443)上运行并使用子路由:
mainRoute := mux.NewRouter()
mainRoute.StrictSlash(true)
mainRoute.Handle("/", http.RedirectHandler("/static/", 302))
mainRoute.PathPrefix("/static/").Handler(http.StripPrefix("/static", *fh))
// Bind API Routes
apiRoute := mainRoute.PathPrefix("/api").Subrouter()
apiProductRoute := apiRoute.PathPrefix("/products").Subrouter()
apiProductRoute.Handle("/", handler(listProducts)).Methods("GET")
Run Code Online (Sandbox Code Playgroud)
功能:
func listProducts(w http.ResponseWriter, r *http.Request) (interface{}, *handleHTTPError) {
vars := mux.Vars(r)
productType, ok := vars["id"]
log.Println(productType)
log.Println(ok)
}
Run Code Online (Sandbox Code Playgroud)
ok是false,我不明白为什么.?type=model我的网址后面做的很简单..
我正在使用Go和Gorilla Web工具包的mux和处理程序包来构建复杂的应用程序,其中一部分需要使用http服务器。Gorilla的mux和handler程序包运行良好,我能够成功启动并运行http服务器,并且记录请求非常简单。
但是,我无法确定如何记录响应。理想情况下,我希望有一种类似于Gorilla的LoggingHandler的机制,可以轻松地“包装”日志记录机制。
是否有一个Golang软件包可以轻松包装/记录响应?有没有一种我没有考虑过的使用Go或Gorilla的功能的方法?
我查看了这个问题Serving static content with a root URL with the Gorilla toolkit并成功使用了那里的答案。
不过,出于开发目的,我想明确声明我想要将哪个文件用作静态文件,如下所示:
router.PathPrefix("/style.css").Handler(http.FileServer(http.Dir("/usr/local/myproject/style.css")))
Run Code Online (Sandbox Code Playgroud)
这也按预期工作。
现在,我想知道,这是否是提供单个显式定义文件的正确方法,或者我应该采取不同的方式?
我有使用gorilla/mux实现的 REST HTTP 处理程序。我正在尝试将它们迁移到 gRPC 中。有一些处理程序执行文件上传和下载。因此,我的客户决定在 gRPC 网关中实现这些处理程序。
我的 mux 处理程序之一处理多个 HTTP 方法,并根据一个处理程序函数中的 HTTP 方法执行操作。示例代码如下所示。
package main
import (
"fmt"
"github.com/gorilla/mux"
"net/http"
)
func main() {
r := mux.NewRouter()
r.HandleFunc(`/doSomething`, func(writer http.ResponseWriter, request *http.Request) {
switch request.Method {
case http.MethodPost:
// create something
fmt.Fprint(writer, "POST")
case http.MethodGet:
// return something
fmt.Fprint(writer, "GET")
case http.MethodPut:
// update something
fmt.Fprint(writer, "PUT")
case http.MethodDelete:
// delete something
fmt.Fprint(writer, "DELETE")
}
})
http.ListenAndServe(`:5000`, r)
}
Run Code Online (Sandbox Code Playgroud)
当我实现类似的 grpc 网关复用处理程序来使用grpc-ecosystem/grpc-gateway/v2.3.0处理这些请求时,我必须编写单独的处理程序函数来处理同一路径的不同 HTTP 方法。示例代码如下。
package …Run Code Online (Sandbox Code Playgroud) 我按照以下示例使用 Golang 和本机包提供 NextJs 前端单页应用程序net/http:
import (
"embed"
"io/fs"
"log"
"net/http"
"runtime/pprof"
)
//go:embed nextjs/dist
//go:embed nextjs/dist/_next
//go:embed nextjs/dist/_next/static/chunks/pages/*.js
//go:embed nextjs/dist/_next/static/*/*.js
var nextFS embed.FS
func main() {
// Root at the `dist` folder generated by the Next.js app.
distFS, err := fs.Sub(nextFS, "nextjs/dist")
if err != nil {
log.Fatal(err)
}
// The static Next.js app will be served under `/`.
http.Handle("/", http.FileServer(http.FS(distFS)))
// The API will be served under `/api`.
http.HandleFunc("/api", handleAPI)
// Start HTTP server …Run Code Online (Sandbox Code Playgroud) 我有一个 Nuxt 3 (^3.0.0-rc.11) 前端和一个 Golang Echo v4 后端 API。
该属性在 nuxt.config.ts 文件中ssr设置,因此当我运行时,我可以从 echo API 提供静态生成的文件,并且我从后端发送的会话 cookie 按预期在浏览器中设置。falsenpm run generate
但是,当我npm run dev从 nuxt 运行时,浏览器中没有设置 cookie,即使我可以在响应标头中看到它(在 Firefox 的网络选项卡下)。
我可能认为它不适用于开发服务器,因为 nuxt 正在端口上运行:3000并且 echo on :1323,并且可能存在 CORS 问题?
我尝试按照“为跨源请求设置 cookie”中的提示进行操作,但无济于事。我不确定这是否是我的情况的问题。
我什至尝试从v3.nuxtjs.org创建 nuxt 可组合项,但同样,我不确定这是否是问题所在。
服务器.go
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
AllowOrigins: []string{"http://localhost:3000"},
AllowHeaders: []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept},
AllowCredentials: true,
}))
Run Code Online (Sandbox Code Playgroud)
会话.go
session, _ := store.Get(c.Request(), "session")
session.Options = &sessions.Options{
Path: "/",
MaxAge: 86400 * 7, …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 Gorilla Mux 在 Go 中开发一个简单的 REST API。
我有main.go,它注册了上面的简单路径并启动服务器以侦听端口 3000。
func main() {
router := mux.NewRouter().StrictSlash(true)
sub := router.PathPrefix("/api/v1").Subrouter()
handlers.RegisterRoutes(sub)
log.Fatal(http.ListenAndServe(":3000", router))
}
Run Code Online (Sandbox Code Playgroud)
另一个通用handlers.go文件中的基本处理程序注册方法
func RegisterRoutes(sub *mux.Router) {
user.RegisterRoutes(sub)
}
Run Code Online (Sandbox Code Playgroud)
还有user.handler.go文件,它注册了“/user”子路由:
func RegisterRoutes(sub *mux.Router) {
userRoutes := sub.StrictSlash(true).Path("/users").Subrouter()
userRoutes.Methods("POST").HandlerFunc(getUsers)
userRoutes.Methods("GET").HandlerFunc(getUsers)
}
func getUsers(w http.ResponseWriter, r *http.Request) {
user := User{Name: "test", Password: "test"}
fmt.Printf("%+v\n", r.Method)
json.NewEncoder(w).Encode(user)
}
Run Code Online (Sandbox Code Playgroud)
我正在测试我在上面设置的路径,并提出了一个奇怪的行为:
测试 - GET - localhost:3000/api/v1/users => 在控制台打印 GET。(如预期) 测试 - GET - localhost:3000/api/v1/users/ => 在控制台中打印 GET。(如预期) …
是否可以在 wasm over go 中编写 Websocket 客户端?我试过使用gorilla/websocket,但没有成功:
func main() {
ws := func(this js.Value, inputs []js.Value) interface{} {
go func() {
wsDial, r, err := websocket.DefaultDialer.Dial("ws://localhost:3000/ws", nil)
fmt.Println(wsDial, r, err)
}()
return nil
}
js.Global().Set("ws", js.FuncOf(ws))
select {}
}
Run Code Online (Sandbox Code Playgroud)
调用时出现以下错误ws():
dial tcp: Protocol not available
Run Code Online (Sandbox Code Playgroud)