Handling HTTP requests
The applications usually use the URL paths and HTTP methods to define the behavior of the application. This recipe will illustrate how to leverage the standard library for handling different URLs and methods.
How to do it...
- Open the console and create the folder
chapter09/recipe05
. - Navigate to the directory.
- Create the
handle.go
file with the following content:
package main import ( "fmt" "net/http" ) func main() { mux := http.NewServeMux() mux.HandleFunc("/user", func(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodGet { fmt.Fprintln(w, "User GET") } if r.Method == http.MethodPost { fmt.Fprintln(w, "User POST") } }) // separate handler itemMux := http.NewServeMux() itemMux.HandleFunc("/items/clothes", func(w http.ResponseWriter, ...