github.com/johnnyeven/libtools@v0.0.0-20191126065708-61829c1adf46/courier/transport_http/cors.go (about)

     1  package transport_http
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  	"net/url"
     7  	"strconv"
     8  	"strings"
     9  	"time"
    10  
    11  	"github.com/johnnyeven/libtools/courier/httpx"
    12  )
    13  
    14  func setCORS(headers *http.Header, req *http.Request) {
    15  	referer, err := url.Parse(req.Referer())
    16  	credentials := "false"
    17  	origin := "*"
    18  	if err == nil {
    19  		credentials = "true"
    20  		origin = fmt.Sprintf("%s://%s:%s", referer.Scheme, referer.Hostname(), referer.Port())
    21  	}
    22  	headers.Set("Access-Control-Allow-Credentials", credentials)
    23  	headers.Set("Access-Control-Allow-Origin", origin)
    24  	headers.Set("Access-Control-Allow-Methods", strings.Join([]string{
    25  		http.MethodGet,
    26  		http.MethodPut,
    27  		http.MethodPost,
    28  		http.MethodHead,
    29  		http.MethodDelete,
    30  		http.MethodPatch,
    31  	}, ","))
    32  	headers.Set("Access-Control-Allow-Headers", strings.Join([]string{
    33  		"Origin",
    34  		httpx.HeaderContentType,
    35  		"Content-Length",
    36  		"Authorization",
    37  		"AppToken",
    38  		"AccessKey",
    39  	}, ","))
    40  	headers.Set("Access-Control-Max-Age", strconv.FormatInt(int64(12*time.Hour/time.Second), 10))
    41  }