Handling HTTP Methods

Duration: 10 min  •  Difficulty: Medium

In the previous topic, our router only cared about the Address (URL), not the Method of access.

The Problem

By default, mux.HandleFunc("/users", ...) will accept ALL types of requests:

  • GET /users (Get user data) -> Allowed
  • POST /users (Create new user) -> Allowed
  • DELETE /users (Delete user) -> Allowed
  • However, we might want different logic for each method.

    Solution: Switch Case

    Since standard Go is very minimalist, we don't write app.Get() or app.Post() like in other frameworks. We perform manual checks inside the handler using switch.

    How it Works

    We check the content of r.Method (Request Method).

    MAIN.GO
    package main
    import (
    "fmt"
    "net/http"
    )
    func usersHandler(w http.ResponseWriter, r *http.Request) {
    // Check which method the user is using
    switch r.Method {
    case "GET":
    // Logic for retrieving data
    w.Write([]byte("List of all users..."))
    case "POST":
    // Logic for saving data
    w.Write([]byte("Successfully created new user!"))
    default:
    // if method other than GET/POST (e.g., DELETE), we reject.
    http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
    }
    }
    func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/users", usersHandler)
    fmt.Println("Test with Postman/Curl to localhost:8080/users")
    http.ListenAndServe(":8080", mux)
    }

    Why Manual?

    It might seem complicated compared to other frameworks, but this way the programmer understands perfectly the program's flow. There is no "magic" behind the scenes. The code becomes very explicit and easy to debug.