support cors in rest server
parent
1c1e4bca86
commit
fe0d0687f5
@ -0,0 +1,29 @@
|
|||||||
|
package rest
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
allowOrigin = "Access-Control-Allow-Origin"
|
||||||
|
allOrigin = "*"
|
||||||
|
allowMethods = "Access-Control-Allow-Methods"
|
||||||
|
allowHeaders = "Access-Control-Allow-Headers"
|
||||||
|
headers = "Content-Type, Content-Length, Origin"
|
||||||
|
methods = "GET, HEAD, POST, PATCH, PUT, DELETE"
|
||||||
|
separator = ", "
|
||||||
|
)
|
||||||
|
|
||||||
|
func CorsHandler(origins ...string) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if len(origins) > 0 {
|
||||||
|
w.Header().Set(allowOrigin, strings.Join(origins, separator))
|
||||||
|
} else {
|
||||||
|
w.Header().Set(allowOrigin, allOrigin)
|
||||||
|
}
|
||||||
|
w.Header().Set(allowMethods, methods)
|
||||||
|
w.Header().Set(allowHeaders, headers)
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
})
|
||||||
|
}
|
@ -0,0 +1,27 @@
|
|||||||
|
package rest
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCorsHandler(t *testing.T) {
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
handler := CorsHandler()
|
||||||
|
handler.ServeHTTP(w, nil)
|
||||||
|
assert.Equal(t, http.StatusNoContent, w.Result().StatusCode)
|
||||||
|
assert.Equal(t, allOrigin, w.Header().Get(allowOrigin))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCorsHandlerWithOrigins(t *testing.T) {
|
||||||
|
origins := []string{"local", "remote"}
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
handler := CorsHandler(origins...)
|
||||||
|
handler.ServeHTTP(w, nil)
|
||||||
|
assert.Equal(t, http.StatusNoContent, w.Result().StatusCode)
|
||||||
|
assert.Equal(t, strings.Join(origins, separator), w.Header().Get(allowOrigin))
|
||||||
|
}
|
Loading…
Reference in New Issue