Home > Articles

  • Print
  • + Share This
This chapter is from the book

Responding to Different Types of Requests

As well as being able to respond to requests for different content types, HTTP servers typically need to be able to respond to different types of requests. The types of requests that a client may make are defined in the HTTP specification and include GET, POST, PUT, and DELETE. To create a HTTP server in Go that responds to different types of requests, a similar technique to serve multiple content types may be used, as shown in Listing 18.5. In the handler function for a route, the request type can be checked and then a switch can determine how to handle the request.

LISTING 18.5 Responding to Different Types of Requests

 1:  package main
 2:
 3:  import (
 4:      "net/http"
 5:  )
 6:
 7:  func helloWorld(w http.ResponseWriter, r *http.Request) {
 8:      if r.URL.Path != "/" {
 9:              http.NotFound(w, r)
10:              return
11:      }
12:      switch r.Method {
13:      case "GET":
14:              w.Write([]byte("Received a GET request\n"))
15:      case "POST":
16:              w.Write([]byte("Received a POST request\n"))
17:      default:
18:              w.WriteHeader(http.StatusNotImplemented)
19:              w.Write([]byte(http.StatusText(http.StatusNotImplemented)) + "\n")
20:      }
21:
22:  }
23:
24:  func main() {
25:      http.HandleFunc("/", helloWorld)
26:      http.ListenAndServe(":8000", nil)
27:  }

The amendments to the server can be explained as follows:

  • Instead of using content type to switch the response, the server uses the request method.

  • The switch statement sends a response depending on the type of request.

  • In this example, a plain text response is sent to indicate the type of request.

  • If the method is not a GET or a POST, it falls through to the default. This sends a 501 Not Implemented HTTP response. The 501 code means the server does not understand or does not support the HTTP method sent by the client.

Running the server shows that both GET and POST requests may now be made. To change the request type using curl, the -X option is used.

  • + Share This
  • 🔖 Save To Your Account