Search code examples
restgomux

Golang gorilla mux REST api is giving 405 error on using PUT and DELETE methods


Golang gorilla mux REST api is giving 405 error on using PUT and DELETE methods. But GET and POST methods are working fine.

I used postman to test my REST api server, GET and POST requests works fine but PUT and DELETE methods not working and giving error 405

...
...
func updateBook(w http.ResponseWriter, r *http.Request){
    w.Header().Set("Content-Type", "application/json")
    params := mux.Vars(r)
    for index, item := range books {
        if item.ID == params["id"]{
            books = append(books[:index], books[index+1:]...)
            var book Book
            _ = json.NewDecoder(r.Body).Decode(&book)
            book.ID = params["id"]
            books = append(books, book)
            json.NewEncoder(w).Encode(books)
            return
        }
    }
}

func deleteBook(w http.ResponseWriter, r *http.Request){
    w.Header().Set("Content-Type", "application/json")
    params := mux.Vars(r)
    for index, item := range books {
        if item.ID == params["id"]{
            books = append(books[:index], books[index+1:]...)
            break
        }
    }
    json.NewEncoder(w).Encode(books)
}



func main() {
    // INIT router
    r := mux.NewRouter()

    // Mock data
    books = append(books, Book{
    ID: "1",
    Isbn: "43432",
    Title: "Book first",
    Author: &Author{
        FirstName: "Vishal",
        LastName: "Sharma",
    },
    })

    // Route handlers / Endpoints
    r.HandleFunc("/api/books", getbooks).Methods("GET")
    r.HandleFunc("/api/books/{id}", getBook).Methods("GET")
    r.HandleFunc("/api/books", createBook).Methods("POST")
    r.HandleFunc("api/books/{id}", updateBook).Methods("PUT")
    r.HandleFunc("api/books/{id}", deleteBook).Methods("DELETE")

    log.Fatal(http.ListenAndServe(":3000", r))
}

Solution

  • As it was pointed out in the comments, it was a typo.

    r.HandleFunc("api/books/{1}", deleteBook).Methods("DELETE")
    

    i am missing a / forward slash before the api/books/{1}

    correct syntax is

    r.HandleFunc("/api/books/{1}", deleteBook).Methods("DELETE")