0
votes

I was trying to set up a CRUD http API using gorilla-mux library.

I followed a youtube tutorial Implementation is below: -

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))
}

When I do go build on this file, I get below compilation errors -

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

What did I do wrong? What did I miss here? In the tutorial, he was able to build and run the file.

1

1 Answers

3
votes

HanldeFunc type of function takes two paramters you are passing it wrong.

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

}

It should be *http.Request not *http.Response

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

}

Checkout on Go Playground