Go CORS Middleware

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

Go Data 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)
  })
}