package midware

import (
	"net/http"
	"strings"
)

// Cors 跨域
func Cors(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// 设置Vary头部
		w.Header().Set("Vary", "Origin")
		w.Header().Set("Keep-Alive", "timeout=5")

		requestOrigin := r.Header.Get("Origin")
		if requestOrigin == "" {
			next.ServeHTTP(w, r)
			return
		}

		w.Header().Set("Access-Control-Allow-Origin", "*")

		w.Header().Set("Access-Control-Allow-Credentials", "true")

		// OPTIONS
		if r.Method == "OPTIONS" {
			requestMethod := r.Header.Get("Access-Control-Request-Method")
			if requestMethod == "" {
				next.ServeHTTP(w, r)
				return
			}

			// 响应最大时间值
			w.Header().Set("Access-Control-Max-Age", "31536000")

			// 允许方法
			allowMethods := []string{
				"OPTIONS",
				"HEAD",
				"GET",
				"POST",
				"PUT",
				"DELETE",
				"PATCH",
			}
			w.Header().Set("Access-Control-Allow-Methods", strings.Join(allowMethods, ","))

			// 允许请求头
			allowHeaders := []string{
				"Accesstoken",
				"Content-Type",
				"operationtype",
			}
			w.Header().Set("Access-Control-Allow-Headers", strings.Join(allowHeaders, ","))

			w.WriteHeader(204)
			return
		}

		// 暴露请求头
		exposeHeaders := []string{"X-RepeatSubmit-Rest", "AccessToken"}
		w.Header().Set("Access-Control-Expose-Headers", strings.Join(exposeHeaders, ","))

		next.ServeHTTP(w, r)
	})
}
