HTTP methods, headers and status codes
HTTP methods, headers and status codes
HTTP is a request/response protocol. A request specifies a method (the intended operation), URL and headers (metadata), and may carry a body. The response has a status code, headers and potentially a body. GET retrieves a representation; POST asks the resource to process submitted data. The local test server below replies to requests without contacting the internet. Use the supplied client, close the response body and check errors. Panic stops these tiny demonstrations only.
package main
import ( "fmt" "io" "net/http" "net/http/httptest" "time")
func check(err error) { if err != nil { panic(err) }}func fixture(h http.HandlerFunc) (*httptest.Server, *http.Client) { s := httptest.NewServer(h) c := s.Client() c.Timeout = 2 * time.Second return s, c}func main() { s, c := fixture(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/plain") fmt.Fprint(w, r.Method) }) defer s.Close() res, e := c.Get(s.URL) check(e) defer res.Body.Close() b, e := io.ReadAll(res.Body) check(e) fmt.Println(res.StatusCode, res.Header.Get("Content-Type"), string(b))}httptest.NewServer starts a loopback listener with a temporary port. The handler is a function receiving the request and a response writer; full handler design comes next chapter. Status 200 means OK. Header.Get retrieves the first value, case-insensitively for canonical HTTP headers. ReadAll here is safe only because we control the tiny fixture; the body is a stream.
Expected output:
200 text/plain GETInspect a POST response
package main
import ( "fmt" "net/http" "net/http/httptest" "strings" "time")
func check(err error) { if err != nil { panic(err) }}func fixture(h http.HandlerFunc) (*httptest.Server, *http.Client) { s := httptest.NewServer(h) c := s.Client() c.Timeout = 2 * time.Second return s, c}func main() { s, c := fixture(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("X-Method", r.Method) w.WriteHeader(http.StatusCreated) }) defer s.Close() res, e := c.Post(s.URL, "text/plain", strings.NewReader("note")) check(e) defer res.Body.Close() fmt.Println(res.StatusCode, res.Header.Get("x-method"))}Post supplies the content type and body. A 201 response means the server reports creation; HTTP status is not a guarantee of persistence. Use Header.Set for one value and Add for another value; do not assume every repeated header can be joined with a comma. A HEAD response has no message body even when its Content-Length describes the GET representation.
Expected output:
201 POSTTry it locally
Create a local server returning 204 and header X-Mode: quiet; print both.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HTTP clients 01: HTTP methods, headers and status codes
Check the lesson objective before moving on.
What identifies the intended HTTP operation?
What does 204 represent?