Golang mux 路由器处理程序函数参数



我试图使用gorilla-mux库设置一个CRUD http API。

我关注了一个YouTube教程 实施情况如下: -

package main
import (
"github.com/gorilla/mux"
"net/http"
"log"
)
type Book struct {
Id     string  `json:"id"`
Isbn   string  `json:"isbn"`
Title  string  `json:"title"`
Author *Author `json:"author"`
}
type Author struct {
Firstname string `json:"firstname"`
Lastname  string `json:"lastname"`
}
// Get all books
func getBooks(w http.ResponseWriter, r *http.Response) {
}
// Get single book
func getBook(w http.ResponseWriter, r *http.Response) {
}
// Create a book
func createBook(w http.ResponseWriter, r *http.Response) {
}
// Update a book
func updateBook(w http.ResponseWriter, r *http.Response) {
}
// Delete a book
func deleteBook(w http.ResponseWriter, r *http.Response) {
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/api/books", getBooks).Methods("GET")
r.HandleFunc("/api/book/{id}", getBook).Methods("GET")
r.HandleFunc("/api/book", createBook).Methods("POST")
r.HandleFunc("/api/book/{id}", updateBook).Methods("PUT")
r.HandleFunc("/api/book/{id}", deleteBook).Methods("DELETE")
r.Path("/api/books").Methods("GET").HandlerFunc(getBooks)
log.Fatal(http.ListenAndServe(":8000", r))
}

当我在这个文件上构建时,我得到以下编译错误 -

.

/main.go:49:15: 不能使用 getBooks (类型 func(http.响应编写器, *http.响应)) 作为类型 func(http.ResponseWriter, *http.请求)在参数中为 r.HandleFunc ./main.go:50:15:无法使用 getBook (键入 func(http.ResponseWriter, *http.响应)) 作为类型 func(http.ResponseWriter, *http.请求)在参数中对 r.HandleFunc ./main.go:51:15: 不能使用 createBook (类型 func(http.响应编写器, *http.响应)) 作为类型 func(http.ResponseWriter, *http.请求)在参数中为 r.HandleFunc ./main.go:52:15:无法使用 updateBook (键入 func(http.ResponseWriter, *http.响应)) 作为类型 func(http.ResponseWriter, *http.请求)在参数中对 r.HandleFunc ./main.go:53:15: 不能使用 deleteBook (类型 func(http.响应编写器, *http.响应)) 作为类型 func(http.ResponseWriter, *http.请求)在参数中对 r.HandleFunc

我做错了什么?我在这里错过了什么?在本教程中,他能够构建并运行该文件。

HanldeFunc类型的函数需要两个参数,你传递错了。

// Get all books
func getBooks(w http.ResponseWriter, r *http.Response) {
}

它应该是*http.Request而不是*http.Response

// Get all books
func getBooks(w http.ResponseWriter, r *http.Request) {
}

在Go Playground上结账

最新更新