From 0379c252d1ed57f1901c97f60f38a4f76a517f73 Mon Sep 17 00:00:00 2001
From: Nedyalko Andreev <n@andreev.sh>
Date: Thu, 22 Mar 2018 21:25:53 +0200
Subject: [PATCH] Combine the cors and optionsAndHead middlewares

---
 httpbin/httpbin.go    |  3 +--
 httpbin/middleware.go | 24 +++++++++---------------
 2 files changed, 10 insertions(+), 17 deletions(-)

diff --git a/httpbin/httpbin.go b/httpbin/httpbin.go
index 25f5caf..ad12c29 100644
--- a/httpbin/httpbin.go
+++ b/httpbin/httpbin.go
@@ -174,9 +174,8 @@ func (h *HTTPBin) Handler() http.Handler {
 	var handler http.Handler
 	handler = mux
 	handler = limitRequestSize(h.options.MaxMemory, handler)
-	handler = optionsAndHead(handler)
+	handler = metaRequests(handler)
 	handler = logger(handler)
-	handler = cors(handler)
 	return handler
 }
 
diff --git a/httpbin/middleware.go b/httpbin/middleware.go
index e53bcab..60033fa 100644
--- a/httpbin/middleware.go
+++ b/httpbin/middleware.go
@@ -8,8 +8,16 @@ import (
 	"time"
 )
 
-func optionsAndHead(h http.Handler) http.Handler {
+func metaRequests(h http.Handler) http.Handler {
 	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		origin := r.Header.Get("Origin")
+		if origin == "" {
+			origin = "*"
+		}
+		respHeader := w.Header()
+		respHeader.Set("Access-Control-Allow-Origin", origin)
+		respHeader.Set("Access-Control-Allow-Credentials", "true")
+
 		switch r.Method {
 		case "OPTIONS":
 			w.Header().Set("Access-Control-Allow-Methods", "GET, POST, HEAD, PUT, DELETE, PATCH, OPTIONS")
@@ -31,20 +39,6 @@ func optionsAndHead(h http.Handler) http.Handler {
 	})
 }
 
-func cors(h http.Handler) http.Handler {
-	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
-		origin := r.Header.Get("Origin")
-		if origin == "" {
-			origin = "*"
-		}
-		respHeader := w.Header()
-		respHeader.Set("Access-Control-Allow-Origin", origin)
-		respHeader.Set("Access-Control-Allow-Credentials", "true")
-
-		h.ServeHTTP(w, r)
-	})
-}
-
 func methods(h http.HandlerFunc, methods ...string) http.HandlerFunc {
 	methodMap := make(map[string]struct{}, len(methods))
 	for _, m := range methods {
-- 
GitLab