Golang mux路由器处理函数参数

时间:2018-02-28 18:30:52

标签: go 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.ResponseWriter,   * http.Response))作为类型func(http.ResponseWriter,* http.Request)在r.HandleFunc ./main.go:50:15的参数中:不能使用getBook(类型)   func(http.ResponseWriter,* http.Response))作为类型   r.HandleFunc参数中的func(http.ResponseWriter,* http.Request)   ./main.go:51:15:无法使用createBook(类型为func(http.ResponseWriter,   * http.Response))作为类型func(http.ResponseWriter,* http.Request)在r.HandleFunc ./main.go:52:15的参数中:不能使用updateBook(类型)   func(http.ResponseWriter,* http.Response))作为类型   r.HandleFunc参数中的func(http.ResponseWriter,* http.Request)   ./main.go:53:15:无法使用deleteBook(类型为func(http.ResponseWriter,   * http.Response))作为r.HandleFunc参数中的类型func(http.ResponseWriter,* http.Request)

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

1 个答案:

答案 0 :(得分:3)

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

相关问题