gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 02:31:53 32 4
gpt4 key购买 nike

我试图使用 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

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

最佳答案

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 结帐

关于Golang mux 路由器处理程序函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49036269/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com