github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/service/api/server/http/cors.go (about)

     1  // Copyright 2020 Asim Aslam
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     https://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  //
    15  // Original source: github.com/micro/go-micro/v3/api/server/cors/cors.go
    16  
    17  package http
    18  
    19  import (
    20  	"net/http"
    21  )
    22  
    23  // CombinedCORSHandler wraps a server and provides CORS headers
    24  func CombinedCORSHandler(h http.Handler) http.Handler {
    25  	return corsHandler{h}
    26  }
    27  
    28  type corsHandler struct {
    29  	handler http.Handler
    30  }
    31  
    32  func (c corsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    33  	SetHeaders(w, r)
    34  
    35  	if r.Method == "OPTIONS" {
    36  		return
    37  	}
    38  
    39  	c.handler.ServeHTTP(w, r)
    40  }
    41  
    42  // SetHeaders sets the CORS headers
    43  func SetHeaders(w http.ResponseWriter, r *http.Request) {
    44  	set := func(w http.ResponseWriter, k, v string) {
    45  		if v := w.Header().Get(k); len(v) > 0 {
    46  			return
    47  		}
    48  		w.Header().Set(k, v)
    49  	}
    50  
    51  	if origin := r.Header.Get("Origin"); len(origin) > 0 {
    52  		set(w, "Access-Control-Allow-Origin", origin)
    53  	} else {
    54  		set(w, "Access-Control-Allow-Origin", "*")
    55  	}
    56  
    57  	set(w, "Access-Control-Allow-Credentials", "true")
    58  	set(w, "Access-Control-Allow-Methods", "POST, PATCH, GET, OPTIONS, PUT, DELETE")
    59  	set(w, "Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, Micro-Namespace")
    60  }