我从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[]为map[ID]
在不同的文件中时:
和前一个一样,我收到了一个空的map[]
这是我的文件 struct
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[]应该是什么样子的map[].
我寻找了解决方案,但似乎需要对这些替代方案做出更多解释.我已经查到了r.URL.Query
,但他们面临的问题是使用不同的路由 struct .
我也在寻找另一种‘mux.RouteMatch’的替代品,但我想我需要一点解释.