卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章34935本站已运行393

为什么 mux.Vars() 返回空映射

为什么 mux.vars() 返回空映射

php小编柚子在这里为大家解答一个常见的问题:为什么在使用mux.Vars()方法时返回的是一个空映射?这个问题在开发过程中可能会遇到,通常是由于一些配置或使用上的问题所导致的。在本文中,我们将详细讨论可能的原因,并给出解决方案,帮助开发者快速解决这个问题。让我们一起来看看吧!

问题内容

我从 mux.vars[] 得到一个空的 map[]。

跟踪问题后,似乎是一个空的map[]通过了我的多个文件。

在同一个文件中:我已将另一个文件作为模块导入(我相信)在 import

package main

import(
"github.com/ny0ttt/go-bookstore/pkg/controllers"
//note that this is imported from powershell, go mod init "github.com/ny0ttt/go-bookstore"
)

运行 go run main.go 后,我获得了map[]作为ma​​p[id]

在不同的文件中:

按照与上一个相同的导入方式,我收到一个空的ma​​p[]

这是我的文件结构


go-test/cmd/main/main.exe
go-test/cmd/main/main.go
go-test/pkg/config/app.go
go-test/pkg/models/models.go
go-test/pkg/controllers/book-controller.go
go-test/pkg/utils/utils.go
go-test/go.sum
go-test/go.mod

我的 mod 文件包含

module github.com/ny0ttt/go-bookstore

go 1.20

require (
    github.com/go-sql-driver/mysql v1.5.0
    github.com/gorilla/mux v1.8.0
    github.com/jinzhu/gorm v1.9.16
)

require github.com/jinzhu/inflection v1.0.0 // indirect

这是我的代码:

在我的控制器中

func getbookbyid(w http.responsewriter, r *http.request){
    vars := mux.vars(r)
    bookid := vars["id"]
    id, err := strconv.parseint(bookid, 0, 0)
    if err != nil{
        fmt.println("error while parsing")
        fmt.println(r)
        fmt.println(bookid)
        fmt.println(vars)
    }
    bookdetails, _ := models.getbookbyid(id) //mthis model returns 2 variable but we will be using only one of them. refer models
    res, _ := json.marshal(bookdetails)
    w.header().set("content-type","pkglication/json")
    w.writeheader(http.statusok)
    w.write(res)
}

在我的路线中

func main() {
    r := mux.newrouter()
    
    //routes.registerbookstoreroutes(r)
    r.handlefunc("/book/", controllers.getbook).methods("get")
    r.handlefunc("/book/", controllers.createbook).methods("post")
    r.handlefunc("/book/{id}", controllers.getbookbyid).methods("get")
    r.handlefunc("/book/{bookid}", controllers.updatebook).methods("put")
    r.handlefunc("/book/{bookid}", controllers.deletebook).methods("delete")
        http.handle("/", r)
    log.fatal(http.listenandserve(":2222", r)) // creating a server
}

输出

error while parsing
&{GET /book/1 HTTP/1.1 1 1 map[Accept:[*/*] Accept-Encoding:[gzip, deflate, br] Connection:[keep-alive] Postman-Token:[a28eebe1-b6d4-4aff-89ed-d3b93a4ed1df] User-Agent:[PostmanRuntime/7.32.3]] {} <nil> 0 [] false :2222 map[] map[] <nil> map[] 127.0.0.1:52035 /book/1 <nil> <nil> <nil> 0xc000282a20}

map[]

注意:我打印出这些值,以便我可以追踪哪里出错了,*http.request 没有映射任何值?我不确定返回 http.request 的 map[] 应该是什么样子。

我寻找解决方案,但似乎我需要对这些替代方案进行更多解释。我查找了 r.url.query 但他们面临的问题是使用不同的路由结构时。

我还使用 `mux.routematch` 寻找另一种替代方案,但我认为我可以使用一些解释。

解决方法

问题已解决

我只是将我的项目移动到桌面上(我相信您可以移动到任何您想要的位置,只要您不需要管理员权限来访问该目录)并且它可以工作。

从现在开始,我将继续在可访问的目录中探索项目。谢谢。

卓越飞翔博客
上一篇: 需要帮助从 mongodb 文档获取元素并使用 go mongo 驱动程序更新其值
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏