2

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))
}
3
  • go version is 1.14 Commented May 18, 2020 at 14:21
  • Aren't you missing the leading slashes in the endpoint pattern strings for those two methods? And if indeed that is the cause of the problem feel free to close/delete the question as the problem was caused by a typo. Commented May 18, 2020 at 14:28
  • Thank you @mkopriva, it was the typo. Now it's working fine. Commented May 18, 2020 at 14:35

1 Answer 1

4

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")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.