1// Copyright 2013 The Prometheus Authors 2// Licensed under the Apache License, Version 2.0 (the "License"); 3// you may not use this file except in compliance with the License. 4// You may obtain a copy of the License at 5// 6// http://www.apache.org/licenses/LICENSE-2.0 7// 8// Unless required by applicable law or agreed to in writing, software 9// distributed under the License is distributed on an "AS IS" BASIS, 10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11// See the License for the specific language governing permissions and 12// limitations under the License. 13 14package httputil 15 16import ( 17 "net/http" 18 "regexp" 19) 20 21var corsHeaders = map[string]string{ 22 "Access-Control-Allow-Headers": "Accept, Authorization, Content-Type, Origin", 23 "Access-Control-Allow-Methods": "GET, POST, OPTIONS", 24 "Access-Control-Expose-Headers": "Date", 25 "Vary": "Origin", 26} 27 28// Enables cross-site script calls. 29func SetCORS(w http.ResponseWriter, o *regexp.Regexp, r *http.Request) { 30 origin := r.Header.Get("Origin") 31 if origin == "" { 32 return 33 } 34 35 for k, v := range corsHeaders { 36 w.Header().Set(k, v) 37 } 38 39 if o.String() == "^(?:.*)$" { 40 w.Header().Set("Access-Control-Allow-Origin", "*") 41 return 42 } 43 44 if o.MatchString(origin) { 45 w.Header().Set("Access-Control-Allow-Origin", origin) 46 } 47} 48