Dev Skills
Go tests·8 questions

Web services

net/http routing, handlers, middleware, shutdown, and project layout.

1 / 8

What did Go 1.22 add that removed most of the reason to use a web framework?

All questions with explanations (answers shown)
  1. 1. What did Go 1.22 add that removed most of the reason to use a web framework?

    Answer: Method and path-parameter routing: mux.HandleFunc("GET /users/{id}", h)

    Before 1.22 ServeMux matched paths only, so you routed methods by hand. Now r.PathValue("id") gets the parameter and the framework buys you very little.

  2. 2. What is the correct order inside a handler?

    Answer: Set headers, then WriteHeader, then write the body

    Headers set after WriteHeader are silently dropped, and writing a body implies WriteHeader(200). Always return right after writing an error, or you get "superfluous WriteHeader".

  3. 3. What is wrong with http.ListenAndServe(":8080", mux) in production?

    Answer: The zero-value server has no timeouts, so one slow client can hold a connection forever

    Configure http.Server with ReadHeaderTimeout (the Slowloris defence), ReadTimeout, WriteTimeout and IdleTimeout.

  4. 4. What is a middleware in Go?

    Answer: A function taking an http.Handler and returning an http.Handler

    That is the whole mechanism. You compose by nesting, so no framework is required.

  5. 5. Your recover middleware wraps every handler. A goroutine you started inside a handler panics. What happens?

    Answer: It kills the whole process — a parent recover cannot catch it

    Recover only works in the panicking goroutine’s own deferred function. Every long-lived goroutine you launch needs its own defer recover().

  6. 6. Why must signal.Notify’s channel be buffered?

    Answer: signal.Notify never blocks, so an unbuffered channel with nobody receiving yet drops the signal

    make(chan os.Signal, 1). Get this wrong and your graceful shutdown silently never triggers.

  7. 7. A handler calls w.Write(body) and then w.WriteHeader(http.StatusCreated). What does the client get?

    Answer: 200 OK, and the server logs "superfluous response.WriteHeader call"

    The first Write sends a 200 if no status was set. After that the status is fixed, so the later WriteHeader only produces a log line. Call WriteHeader(201) before writing the body.

  8. 8. You start srv := &http.Server{Addr: ":8080", Handler: mux} with no timeouts. Which one fix matters most?

    Answer: Set ReadHeaderTimeout, so a client that sends headers very slowly cannot hold a connection open forever

    With no timeouts, a slow client (Slowloris) can keep many connections open by trickling headers. ReadHeaderTimeout closes them. Set ReadTimeout, WriteTimeout and IdleTimeout too.