github.com/ghodss/etcd@v0.3.1-0.20140417172404-cc329bfa55cb/http/cors.go (about)

     1  /*
     2  Copyright 2013 CoreOS Inc.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8       http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package http
    18  
    19  import (
    20  	"fmt"
    21  	"net/http"
    22  	"net/url"
    23  )
    24  
    25  type CORSInfo map[string]bool
    26  
    27  func NewCORSInfo(origins []string) (*CORSInfo, error) {
    28  	// Construct a lookup of all origins.
    29  	m := make(map[string]bool)
    30  	for _, v := range origins {
    31  		if v != "*" {
    32  			if _, err := url.Parse(v); err != nil {
    33  				return nil, fmt.Errorf("Invalid CORS origin: %s", err)
    34  			}
    35  		}
    36  		m[v] = true
    37  	}
    38  
    39  	info := CORSInfo(m)
    40  	return &info, nil
    41  }
    42  
    43  // OriginAllowed determines whether the server will allow a given CORS origin.
    44  func (c CORSInfo) OriginAllowed(origin string) bool {
    45  	return c["*"] || c[origin]
    46  }
    47  
    48  type CORSHandler struct {
    49  	Handler http.Handler
    50  	Info    *CORSInfo
    51  }
    52  
    53  // addHeader adds the correct cors headers given an origin
    54  func (h *CORSHandler) addHeader(w http.ResponseWriter, origin string) {
    55  	w.Header().Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
    56  	w.Header().Add("Access-Control-Allow-Origin", origin)
    57  }
    58  
    59  // ServeHTTP adds the correct CORS headers based on the origin and returns immediatly
    60  // with a 200 OK if the method is OPTIONS.
    61  func (h *CORSHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    62  	// Write CORS header.
    63  	if h.Info.OriginAllowed("*") {
    64  		h.addHeader(w, "*")
    65  	} else if origin := req.Header.Get("Origin"); h.Info.OriginAllowed(origin) {
    66  		h.addHeader(w, origin)
    67  	}
    68  
    69  	if req.Method == "OPTIONS" {
    70  		w.WriteHeader(http.StatusOK)
    71  		return
    72  	}
    73  
    74  	h.Handler.ServeHTTP(w, req)
    75  }