Go CORS Middleware

Implement CORS middleware in Go with configurable allowed origins, methods, headers, preflight request handling, and credential support for cross-origin API.

GoData Fetching

Code

snippet
package main

import (
  "net/http"
  "strings"
)

func corsMiddleware(allowedOrigins []string, next http.Handler) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    origin := r.Header.Get("Origin")
    for _, allowed := range allowedOrigins {
      if origin == allowed {
        w.Header().Set("Access-Control-Allow-Origin", origin)
        w.Header().Set("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE")
        w.Header().Set("Access-Control-Allow-Headers", "Content-Type,Authorization")
        break
      }
    }
    if r.Method == "OPTIONS" { w.WriteHeader(http.StatusOK); return }
    next.ServeHTTP(w, r)
  })
}

How it works

All of the logic lives in the function corsMiddleware.

Repetition is confined to for _, allowed := range allowedOrigins — the rest of the file is straight-line.

What to watch for

  • It is dependency-free in the strict sense — the import list, if any, is empty of packages.

Putting it to use

The operative signature is func corsMiddleware(allowedOrigins []string, next http.Handler) http.Handler

The core lines, annotated

if r.Method == "OPTIONS" { w.WriteHeader(http.StatusOK); return }
for _, allowed := range allowedOrigins {
if origin == allowed {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type,Authorization")
break
}
}

Interactive Tools for This Topic

FAQ

Is a package install part of the setup?
No. Installation is unnecessary because only built-in APIs are used. Every import resolves inside the standard library — `net/http`, `strings`. The file defines `corsMiddleware` at load time.