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

Golang mux router handler function arguments

我正在尝试使用 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: cannot use getBooks (type func(http.ResponseWriter, *http.Response)) as type func(http.ResponseWriter, *http.Request) in argument to r.HandleFunc ./main.go:50:15: cannot use getBook (type func(http.ResponseWriter, *http.Response)) as type func(http.ResponseWriter, *http.Request) in argument to r.HandleFunc ./main.go:51:15: cannot use createBook (type func(http.ResponseWriter, *http.Response)) as type func(http.ResponseWriter, *http.Request) in argument to r.HandleFunc ./main.go:52:15: cannot use updateBook (type func(http.ResponseWriter, *http.Response)) as type func(http.ResponseWriter, *http.Request) in argument to r.HandleFunc ./main.go:53:15: cannot use deleteBook (type func(http.ResponseWriter, *http.Response)) as type func(http.ResponseWriter, *http.Request) in argument to r.HandleFunc

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

HandleFunc 类型的函数有两个参数,你传递错了。

// 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