github.com/jpetazzo/etcd@v0.2.1-0.20140113055439-97f1363afac5/server/cors_handler.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 server
    18  
    19  import (
    20  	"fmt"
    21  	"net/http"
    22  	"net/url"
    23  
    24  	"github.com/gorilla/mux"
    25  )
    26  
    27  type corsHandler struct {
    28  	router      *mux.Router
    29  	corsOrigins map[string]bool
    30  }
    31  
    32  // AllowOrigins sets a comma-delimited list of origins that are allowed.
    33  func (s *corsHandler) AllowOrigins(origins []string) error {
    34  	// Construct a lookup of all origins.
    35  	m := make(map[string]bool)
    36  	for _, v := range origins {
    37  		if v != "*" {
    38  			if _, err := url.Parse(v); err != nil {
    39  				return fmt.Errorf("Invalid CORS origin: %s", err)
    40  			}
    41  		}
    42  		m[v] = true
    43  	}
    44  	s.corsOrigins = m
    45  
    46  	return nil
    47  }
    48  
    49  // OriginAllowed determines whether the server will allow a given CORS origin.
    50  func (c *corsHandler) OriginAllowed(origin string) bool {
    51  	return c.corsOrigins["*"] || c.corsOrigins[origin]
    52  }
    53  
    54  // addHeader adds the correct cors headers given an origin
    55  func (h *corsHandler) addHeader(w http.ResponseWriter, origin string) {
    56  	w.Header().Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
    57  	w.Header().Add("Access-Control-Allow-Origin", origin)
    58  }
    59  
    60  // ServeHTTP adds the correct CORS headers based on the origin and returns immediatly
    61  // with a 200 OK if the method is OPTIONS.
    62  func (h *corsHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    63  	// Write CORS header.
    64  	if h.OriginAllowed("*") {
    65  		h.addHeader(w, "*")
    66  	} else if origin := req.Header.Get("Origin"); h.OriginAllowed(origin) {
    67  		h.addHeader(w, origin)
    68  	}
    69  
    70  	if req.Method == "OPTIONS" {
    71  		w.WriteHeader(http.StatusOK)
    72  		return
    73  	}
    74  
    75  	h.router.ServeHTTP(w, req)
    76  }