Example #1
0
func TestMatchOrigin(t *testing.T) {
	data := []struct {
		Origin string
		Spec   string
		Result bool
	}{
		{"http://example.com", "*", true},
		{"http://example.com", "http://example.com", true},
		{"http://example.com", "https://example.com", false},
		{"http://test.example.com", "*.example.com", true},
		{"http://test.example.com:80", "*.example.com", false},
		{"http://test.example.com:80", "http://test.example.com*", true},
	}

	for _, test := range data {
		result := cors.MatchOrigin(test.Origin, test.Spec)
		if result != test.Result {
			t.Errorf("cors.MatchOrigin(%s, %s) should return %t", test.Origin, test.Spec, test.Result)
		}
	}
}
Example #2
0
// handleSpecOrigin applies the CORS response headers corresponding to the origin.
func handleSpecOrigin(h goa.Handler) goa.Handler {

	return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
		origin := req.Header.Get("Origin")
		if origin == "" {
			// Not a CORS request
			return h(ctx, rw, req)
		}
		if cors.MatchOrigin(origin, "*") {
			ctx = goa.WithLogContext(ctx, "origin", origin)
			rw.Header().Set("Access-Control-Allow-Origin", origin)
			rw.Header().Set("Access-Control-Allow-Credentials", "false")
			if acrm := req.Header.Get("Access-Control-Request-Method"); acrm != "" {
				// We are handling a preflight request
				rw.Header().Set("Access-Control-Allow-Methods", "GET")
			}
			return h(ctx, rw, req)
		}

		return h(ctx, rw, req)
	}
}