package api

import (
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

// Supoort Rest-API CORS
func Cors(prefix string) gin.HandlerFunc {

	return func(c *gin.Context) {
		if !strings.HasPrefix(c.Request.RequestURI, prefix) {
			c.Next()
			return
		}
		method := c.Request.Method
		if method == "OPTIONS" {
			c.Header("Access-Control-Allow-Headers", "accept, content-type, authorization")
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
			c.Header("Access-Control-Allow-Origin", "*")
			c.AbortWithStatus(http.StatusNoContent)
		} else {
			c.Header("Access-Control-Allow-Origin", "*")
			c.Next()
		}
	}

}
