← All Exercises

API Key HTTP Middleware

intermediatego~25min

Background

Middleware composes cross-cutting HTTP concerns around a handler; wrapping rather than editing each route keeps authentication consistent.

Problem

Implement requireAPIKey(next http.Handler, key string) http.Handler. Requests without a matching X-API-Key header receive 401 with JSON {"error":"unauthorized"}; authorized requests reach next unchanged. An empty configured key rejects everything.

Input

A configured secret key and HTTP requests carrying no header, a wrong header, or the correct X-API-Key header.

Output

401 with a JSON error for rejected requests, or the wrapped handler's response for authorized requests.

Sample tests

Sample 1

Input: request without X-API-Key
Expected: 401 {"error":"unauthorized"}

Sample 2

Input: request with X-API-Key: secret
Expected: 200 ok

Your solution

Learning objective

Compose handlers with middleware and return machine-readable HTTP errors without touching route code.