github.com/anycable/anycable-go@v1.5.1/server/cors.go (about)

     1  package server
     2  
     3  import (
     4  	"net/http"
     5  	"net/url"
     6  	"strings"
     7  )
     8  
     9  func WriteCORSHeaders(w http.ResponseWriter, r *http.Request, origins []string) {
    10  	if len(origins) == 0 {
    11  		w.Header().Set("Access-Control-Allow-Origin", "*")
    12  	} else {
    13  		origin := strings.ToLower(r.Header.Get("Origin"))
    14  		u, err := url.Parse(origin)
    15  		if err == nil {
    16  			for _, host := range origins {
    17  				if host[0] == '*' && strings.HasSuffix(u.Host, host[1:]) {
    18  					w.Header().Set("Access-Control-Allow-Origin", origin)
    19  				}
    20  				if u.Host == host {
    21  					w.Header().Set("Access-Control-Allow-Origin", origin)
    22  				}
    23  			}
    24  		}
    25  	}
    26  
    27  	w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
    28  	w.Header().Set("Access-Control-Allow-Credentials", "true")
    29  	w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, X-Request-ID, Content-Type, Accept, X-CSRF-Token, Authorization")
    30  }