Why does mux.Vars() returns empty map[]

huangapple go评论119阅读模式
英文:

Why does mux.Vars() returns empty map[]

问题

我从mux.Vars[]中得到了一个空的map[]。

在追踪问题之后,似乎是一个空的map[]通过我的多个文件传递。

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

  1. package main
  2. import(
  3. "github.com/Ny0ttt/go-bookstore/pkg/controllers"
  4. //注意这是从powershell导入的,go mod init "github.com/Ny0ttt/go-bookstore"
  5. )

在运行go run main.go之后,我得到了**map[ID]**作为map[]

而在另一个文件中:

与之前导入的方式相同,我收到了一个空的map[]

这是我的文件结构

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文件包含

  1. module github.com/Ny0ttt/go-bookstore
  2. go 1.20
  3. require (
  4. github.com/go-sql-driver/mysql v1.5.0
  5. github.com/gorilla/mux v1.8.0
  6. github.com/jinzhu/gorm v1.9.16
  7. )
  8. require github.com/jinzhu/inflection v1.0.0 // indirect


这是我的代码:

在我的控制器中

  1. func GetBookById(w http.ResponseWriter, r *http.Request){
  2. vars := mux.Vars(r)
  3. bookId := vars["ID"]
  4. ID, err := strconv.ParseInt(bookId, 0, 0)
  5. if err != nil{
  6. fmt.Println("解析错误")
  7. fmt.Println(r)
  8. fmt.Println(bookId)
  9. fmt.Println(vars)
  10. }
  11. bookDetails, _ := models.GetBookById(ID) //此模型返回2个变量,但我们只使用其中一个。参考models
  12. res, _ := json.Marshal(bookDetails)
  13. w.Header().Set("Content-Type","pkglication/json")
  14. w.WriteHeader(http.StatusOK)
  15. w.Write(res)
  16. }

在我的路由中

  1. func main() {
  2. r := mux.NewRouter()
  3. //routes.RegisterBookStoreRoutes(r)
  4. r.HandleFunc("/book/", controllers.GetBook).Methods("GET")
  5. r.HandleFunc("/book/", controllers.CreateBook).Methods("POST")
  6. r.HandleFunc("/book/{ID}", controllers.GetBookById).Methods("GET")
  7. r.HandleFunc("/book/{bookId}", controllers.UpdateBook).Methods("PUT")
  8. r.HandleFunc("/book/{bookId}", controllers.DeleteBook).Methods("DELETE")
  9. http.Handle("/", r)
  10. log.Fatal(http.ListenAndServe(":2222", r)) // 创建一个服务器
  11. }

输出结果

  1. 解析错误
  2. &{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}
  3. map[]

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

我查找了解决方案,但似乎我需要更多关于这些替代方案的解释。我查找了r.URL.Query,但他们遇到的问题是在使用不同的路由结构时。

我还查找了另一种使用mux.RouteMatch的替代方案,但我认为我需要一点解释。

英文:

I get an empty map[] from mux.Vars[].

After tracing the problem, it seems to be an empty map[] passed through my multiple files.

While in the same file: I have imported the other file as a module(I believe) in the import

  1. package main
  2. import(
  3. "github.com/Ny0ttt/go-bookstore/pkg/controllers"
  4. //note that this is imported from powershell, go mod init "github.com/Ny0ttt/go-bookstore"
  5. )

while after running go run main.go, I obtain the map[] as map[ID]

While in a different file:

as per imported like the previous one, I receive an empty map[]

Here is my file structure

> 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

and my mod file contains

  1. module github.com/Ny0ttt/go-bookstore
  2. go 1.20
  3. require (
  4. github.com/go-sql-driver/mysql v1.5.0
  5. github.com/gorilla/mux v1.8.0
  6. github.com/jinzhu/gorm v1.9.16
  7. )
  8. require github.com/jinzhu/inflection v1.0.0 // indirect


Here are my codes :

In my Controller

  1. func GetBookById(w http.ResponseWriter, r *http.Request){
  2. vars := mux.Vars(r)
  3. bookId := vars["ID"]
  4. ID, err := strconv.ParseInt(bookId, 0, 0)
  5. if err != nil{
  6. fmt.Println("error while parsing")
  7. fmt.Println(r)
  8. fmt.Println(bookId)
  9. fmt.Println(vars)
  10. }
  11. bookDetails, _ := models.GetBookById(ID) //mthis model returns 2 variable but we will be using only one of them. refer models
  12. res, _ := json.Marshal(bookDetails)
  13. w.Header().Set("Content-Type","pkglication/json")
  14. w.WriteHeader(http.StatusOK)
  15. w.Write(res)
  16. }

In my Routes

  1. func main() {
  2. r := mux.NewRouter()
  3. //routes.RegisterBookStoreRoutes(r)
  4. r.HandleFunc("/book/", controllers.GetBook).Methods("GET")
  5. r.HandleFunc("/book/", controllers.CreateBook).Methods("POST")
  6. r.HandleFunc("/book/{ID}", controllers.GetBookById).Methods("GET")
  7. r.HandleFunc("/book/{bookId}", controllers.UpdateBook).Methods("PUT")
  8. r.HandleFunc("/book/{bookId}", controllers.DeleteBook).Methods("DELETE")
  9. http.Handle("/", r)
  10. log.Fatal(http.ListenAndServe(":2222", r)) // creating a server
  11. }

The output

  1. error while parsing
  2. &{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}
  3. map[]

Note: I print out the values so I can trace where it did go wrong, *http.Request does not map any values? I am not sure what map[] in return http.Request should look like.

I looked up for solutions, but it seems like i need more explaination on those alternatives. I have look up on r.URL.Query but the problem that they are facing is when using a different route structure.

I have also looked up for another alternative with `mux.RouteMatch` but I think I could use a little bit of explanation.

答案1

得分: 0

问题解决

我只是将我的项目移动到了桌面上(只要你不需要管理员权限来访问目录,你可以将其移动到任何地方),然后它就可以工作了。

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

英文:

Problem Solved

I simply moved my project into the desktop (I am sure you may move wherever you want as long as you don't need administrator power to access the directory ) and it works.

I will continue exploring projects in a accessible directory from now on. Thank you.

huangapple
  • 本文由 发表于 2023年7月8日 08:08:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76640833.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定