http.Request / ResponseWriter
The http.Request argument of an HTTP handler provides information about the incoming request, while http.ResponseWriter provides the interface for writing the response.
Syntax
// Handler function signature
func handler(w http.ResponseWriter, r *http.Request) {
// Read request information
method := r.Method // HTTP method (GET, POST, etc.)
path := r.URL.Path // URL path
query := r.URL.Query() // Query parameters (map[string][]string)
// Write the response
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK) // Set the status code
fmt.Fprintln(w, "Response body")
}
Fields and Methods
| Field / Method | Description |
|---|---|
| r.Method | Returns the HTTP method string (e.g., "GET", "POST"). |
| r.URL.Path | Returns the URL path of the request (e.g., "/api/users"). |
| r.URL.Query() | Returns the query parameters as a map (map[string][]string). |
| r.FormValue(key) | Returns the value for the specified key from the form data or query parameters. |
| r.Body | An io.ReadCloser for the request body. Use it to read POST data. |
| w.Header().Set(key, value) | Sets a response header. Must be called before WriteHeader(). |
| w.WriteHeader(code) | Sets the HTTP status code. Can only be called once. |
| w.Write(data) | Writes a byte slice to the response body. |
Sample Code
package main
import (
"fmt"
"io"
"log"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
// Print the HTTP method
fmt.Println("Method:", r.Method)
// Get a query parameter (?name=Gopher)
name := r.URL.Query().Get("name")
if name == "" {
name = "Guest"
}
// Branch based on the HTTP method
switch r.Method {
case http.MethodGet:
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
fmt.Fprintf(w, "Hello, %s!\n", name)
case http.MethodPost:
// Read the request body
body, _ := io.ReadAll(r.Body)
defer r.Body.Close()
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
fmt.Fprintf(w, "Received: %s\n", string(body))
default:
// Method not allowed
w.WriteHeader(http.StatusMethodNotAllowed)
fmt.Fprintln(w, "Method not allowed")
}
}
func main() {
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
Notes
http.Request contains all information about the incoming request. You can retrieve cookies with r.Cookie(name) and headers with r.Header.Get(key). When working with form data, you must call r.ParseForm() first.
w.WriteHeader() can only be called once, before writing the body. Calling WriteHeader() after writing the body will not change the status code. Response headers must also be set before calling WriteHeader() or the first Write().
If you find any errors or copyright issues, please contact us.