Level: AdvancedInterview

Go REST API Interview Questions: HTTP Servers (Part 19)

Updated 9 min read
Go REST API Interview Questions featured image: routing, middleware and status code cards

These Go REST API interview questions cover net/http, handlers, ServeMux routing, middleware, JSON bodies, status codes, timeouts and HTTP clients. We gathered them from public interview lists, coding rounds and community threads. Then we rewrote them in plain words and grouped them by idea.

This post is questions only, so answer each one in your own words first. When you need help, read Go HTTP server for beginners, Go REST API tutorial and Go middleware examples. Also, finish Part 18 on concurrency patterns first, because every HTTP request runs in its own goroutine.

How to Use These Go REST API Interview Questions

Answer each of these Go REST API interview questions out loud, then try a small handler with httptest. Most HTTP bugs show up at the edges, such as a missing timeout or a body that nobody closed. Finally, try the scenario questions, since they come from real APIs.

The table below lists each section and its number of questions.

SectionWhat it testsQuestions
net/http basicsHandler, ServeMux and Server15
Requests and responsesPaths, JSON bodies and limits15
MiddlewareLogging, auth and recovery14
API designStatus codes, versions and pagination15
HTTP clientsTimeouts, retries and connection reuse14
REST coding tasksClassic interview programs14
Go REST API Interview Questions diagram showing six question areas from net/http to coding tasks
The six areas covered in this question list, from net/http to coding tasks.

Go REST API Interview Questions on net/http

Before you answer, study Go HTTP server for beginners. These Go REST API interview questions start with the building blocks of every Go web server.

  1. What is the http.Handler interface, and which method does it have?
  2. How does http.HandlerFunc turn a plain function into a handler?
  3. What does http.ServeMux do with an incoming request?
  4. Why should you avoid http.DefaultServeMux in production code?
  5. What changed in ServeMux patterns in Go 1.22, such as GET /items/{id}?
  6. How do you read a path value with r.PathValue?
  7. Which pattern wins when two patterns match the same path?
  8. Why does each request run in its own goroutine, and what does that mean for shared data?
  9. What does http.ListenAndServe do, and why is a custom http.Server better?
  10. Which timeout fields does http.Server have, and what does each one protect?
  11. What is ReadHeaderTimeout, and why does it stop slow clients?
  12. How does Server.Shutdown let active requests finish?
  13. When would you use a third-party router such as chi instead of ServeMux?
  14. Scenario: when a server keeps thousands of idle connections open, which settings would you check?
  15. Scenario: when a deploy cuts off requests in the middle, how would you add graceful shutdown?

Go REST API Interview Questions on Requests and Responses

Before you answer, study Go JSON encoding and decoding and Go input validation. Requests carry user data, so these Go REST API interview questions focus on safe reading and clear replies.

  1. How do you read query parameters and path values in a handler?
  2. How do you decode a JSON request body into a struct?
  3. Why should you limit the body size with http.MaxBytesReader before you decode?
  4. How do you reject unknown JSON fields in a request?
  5. Where should validation happen, in the handler or in a service layer?
  6. Why must you set headers before you call WriteHeader or Write?
  7. What does the superfluous WriteHeader warning mean?
  8. How do you return JSON with the right Content-Type header?
  9. What does http.Error write, and when is it not enough for a JSON API?
  10. How do you send a 201 status with a Location header after a create?
  11. Can you read the request body twice, and how would you do it?
  12. How do you stream a large response without loading it all in memory?
  13. How do you serve static files safely with http.FileServer?
  14. Scenario: when a client sends a 2 GB body to a JSON endpoint, how would you protect the server?
  15. Scenario: when users see a 200 status with an error message inside, how would you fix the handler?

Go REST API Interview Questions on Middleware

Before you answer, study Go middleware examples. Middleware wraps every request, so these Go REST API interview questions check order and side effects.

  1. What is middleware in Go, and so what signature does it usually have?
  2. In what order do chained middleware functions run before and after the handler?
  3. How do you write a middleware that logs method, path, status and time taken?
  4. How do you capture the status code that a handler wrote?
  5. Why should a recovery middleware sit near the outside of the chain?
  6. How do you pass a user ID from an auth middleware to the handler?
  7. Where would you add a request ID so that every response and log line carries it?
  8. Can http.TimeoutHandler act as a timeout middleware, and what are its limits?
  9. How do you add CORS headers, and why do browsers send a preflight request?
  10. How do you apply middleware to only one group of routes?
  11. What does a rate limit middleware need to know about each client?
  12. How do you test a middleware on its own?
  13. Scenario: when logs show status 200 for requests that actually failed, what is wrong with the logging middleware?
  14. Scenario: when an auth check runs after the handler already wrote data, how would you reorder the chain?

Go REST API Interview Questions on API Design

Before you answer, study Go REST API tutorial and Go pagination for REST APIs. Good design keeps clients happy, so these Go REST API interview questions test your choices.

  1. What are the main REST ideas, such as resources, methods and statelessness?
  2. Which HTTP methods are safe, and which are idempotent?
  3. How do PUT and PATCH differ for an update?
  4. When would you return 400, 401, 403, 404, 409 and 422?
  5. Why should a delete that finds nothing still be safe to repeat?
  6. How do you design a stable JSON error format, so that all endpoints match?
  7. How do you version an API, in the path or in a header?
  8. What are the trade-offs of offset and cursor pagination?
  9. How do you support filtering and sorting without long query strings?
  10. What is an idempotency key, and when does a payment API need one?
  11. How do you document an API, for example with OpenAPI?
  12. How do ETags and conditional requests save bandwidth?
  13. Should a create endpoint return the full object, and why?
  14. Scenario: when a mobile app retries a create request and makes duplicates, how would you fix the API?
  15. Scenario: when you must rename a JSON field without breaking old clients, how would you plan it?

Go REST API Interview Questions on HTTP Clients

Before you answer, study Go HTTP client and Go retry with backoff. Services call other services all day, so these Go REST API interview questions cover the client side.

  1. Why is the default http.Client risky without a timeout?
  2. How do you set a per-request deadline with a context?
  3. Why must you close resp.Body, even when you do not read it?
  4. Why should you read the body to the end before closing it?
  5. How does http.Transport reuse connections, so that each call is faster?
  6. What do MaxIdleConns and MaxIdleConnsPerHost control?
  7. Why should you create one client and share it?
  8. Which errors are safe to retry, and which are not?
  9. Why should retries use exponential backoff with jitter?
  10. When you test a client, how does httptest.NewServer help?
  11. How do you add a header to every outgoing request with a custom RoundTripper?
  12. How do you check the status code before you decode the body?
  13. Scenario: when a service runs out of file descriptors after calling a partner API, what would you check first?
  14. Scenario: when a partner API is slow, how would you stop your service from hanging with it?

Coding Tasks for HTTP and REST

Before you answer, write each program by hand and test it with httptest. Interviewers watch your status codes and error handling, not only whether the code runs.

  1. Build a CRUD API for books with an in-memory map and a mutex.
  2. Add GET /books/{id} with the Go 1.22 ServeMux pattern.
  3. Write a JSON error helper used by every handler.
  4. Add a logging middleware that prints status and duration.
  5. Add a recovery middleware that turns panics into 500 responses.
  6. Write a health check endpoint for liveness and readiness.
  7. Add pagination with limit and cursor to a list endpoint.
  8. Write a test for a POST handler with httptest.
  9. Build a client that retries a GET three times with backoff.
  10. Add graceful shutdown on SIGTERM with Server.Shutdown.
  11. Limit request bodies to 1 MB and return 413 when larger.
  12. Add a simple API key check as middleware.
  13. Scenario: when an interviewer asks you to build a URL shortener API in 45 minutes, which endpoints would you build first?
  14. Scenario: when the same handler must serve JSON and CSV, how would you choose the format?

Code Reading Questions

Read each program carefully and predict the output before you run it. Then explain the result in your own words.

package main

import (
    "encoding/json"
    "fmt"
    "net/http"
    "net/http/httptest"
)

type Book struct {
    ID    string `json:"id"`
    Title string `json:"title"`
}

func main() {
    books := map[string]Book{"7": {ID: "7", Title: "Go Notes"}}
    mux := http.NewServeMux()
    mux.HandleFunc("GET /books/{id}", func(w http.ResponseWriter, r *http.Request) {
        b, ok := books[r.PathValue("id")]
        if !ok {
            http.Error(w, "book not found", http.StatusNotFound)
            return
        }
        w.Header().Set("Content-Type", "application/json")
        json.NewEncoder(w).Encode(b)
    })

    for _, req := range []*http.Request{
        httptest.NewRequest("GET", "/books/7", nil),
        httptest.NewRequest("GET", "/books/9", nil),
        httptest.NewRequest("POST", "/books/7", nil),
    } {
        rec := httptest.NewRecorder()
        mux.ServeHTTP(rec, req)
        fmt.Printf("%s %s -> %d %q\n", req.Method, req.URL.Path, rec.Code, rec.Body.String())
    }
}
  1. What status code does each request get, and where does the 405 come from?
  2. Why does the JSON body end with a newline character?

The second program shows how middleware wraps a handler.

package main

import (
    "fmt"
    "net/http"
    "net/http/httptest"
)

func logger(name string, next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        fmt.Println("enter", name)
        next.ServeHTTP(w, r)
        fmt.Println("leave", name)
    })
}

func auth(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        if r.Header.Get("X-Token") != "secret" {
            w.WriteHeader(http.StatusUnauthorized)
            return
        }
        next.ServeHTTP(w, r)
    })
}

func main() {
    hello := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        fmt.Println("handler runs")
        w.Write([]byte("hi"))
    })
    h := logger("outer", auth(logger("inner", hello)))

    req := httptest.NewRequest("GET", "/", nil)
    rec := httptest.NewRecorder()
    h.ServeHTTP(rec, req)
    fmt.Println("status:", rec.Code)

    req.Header.Set("X-Token", "secret")
    rec = httptest.NewRecorder()
    h.ServeHTTP(rec, req)
    fmt.Println("status:", rec.Code, rec.Body.String())
}
  1. Which lines print for the first request, and why does the inner logger never run?
  2. In what order do enter and leave print for the second request?

Quick Revision Table for HTTP Status Codes

Use the table below as a final check before your interview. It lists the status codes that interviewers ask about most.

CodeMeaningTypical use
200 OKRequest workedGET or PUT success
201 CreatedNew resource madePOST that creates
204 No ContentWorked, no bodyDELETE success
400 Bad RequestBad input formatInvalid JSON
401 and 403Not logged in, or not allowedAuth checks
404 Not FoundNo such resourceUnknown ID
409 ConflictState clashDuplicate email
500 Internal Server ErrorBug on the serverUnexpected failure

Also, many interviewers ask you to compare PUT and PATCH directly. The diagram below shows the difference side by side.

Go REST API diagram comparing PUT with PATCH
PUT replaces the whole resource, while PATCH changes only the fields you send.

Official Resources

These official pages explain the rules behind these questions.

Quick Recap

  • These Go REST API interview questions cover net/http, requests, middleware, API design, clients and coding tasks.
  • A handler has one ServeHTTP method, and ServeMux matches method and path since Go 1.22.
  • Set server timeouts, limit body size and shut down gracefully.
  • Middleware runs outside in on the way in and inside out on the way back.
  • Pick status codes with care, and keep one JSON error format.
  • Share one http.Client with a timeout, and always close resp.Body.

What’s Next?

By now, you have Go REST API interview questions for servers, middleware and clients. Study the answers in your own notes, then check them against the Go interview topics study guide.

Next up: Go database interview questions (Part 20)