Skip to content

Commit

Permalink
fix: cors
Browse files Browse the repository at this point in the history
  • Loading branch information
GalvinGao committed Jun 30, 2023
1 parent 465bc90 commit abc2f7b
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
5 changes: 4 additions & 1 deletion internal/server/httpserver/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,10 @@ func CreateServiceApp(conf *appconfig.Config) *fiber.App {
Timeout: time.Second * 5,
}))
app.Use(cors.New(cors.Config{
AllowOrigins: "*",
AllowOrigins: "*",
AllowOriginsFunc: func(origin string) bool {
return true
},
AllowMethods: "GET, POST, DELETE, OPTIONS",
AllowHeaders: "Content-Type, Authorization, X-Requested-With, X-Penguin-Variant, sentry-trace",
ExposeHeaders: "Content-Type, X-Penguin-Set-PenguinID, X-Penguin-Upgrade, X-Penguin-Compatible, X-Penguin-Request-ID",
Expand Down
21 changes: 18 additions & 3 deletions test/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,14 +100,29 @@ func TestAPIMeta(t *testing.T) {
})

t.Run("CORS Anonymous Origin", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/PenguinStats/api/v2/config", nil)
req.Header.Set("Origin", "https://penguin-stats.io")

resp := request(
t,
httptest.NewRequest(http.MethodOptions, "/PenguinStats/api/v2/config", nil),
req,
)
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Equal(t, "https://penguin-stats.io", resp.Header.Get("Access-Control-Allow-Origin"))
assert.Equal(t, "true", resp.Header.Get("Access-Control-Allow-Credentials"))
})

t.Run("CORS Origin", func(t *testing.T) {
req := httptest.NewRequest(http.MethodOptions, "/PenguinStats/api/v2/config", nil)
req.Header.Set("Origin", "https://penguin-stats.io")
req.Header.Set("Access-Control-Request-Headers", "Content-Type,Authorization,X-Requested-With,X-Penguin-Variant,sentry-trace")
req.Header.Set("Access-Control-Request-Method", "GET")
req.Header.Set("Access-Control-Request-Credentials", "true")

resp := request(t, req)
assert.Equal(t, http.StatusNoContent, resp.StatusCode)
assert.Equal(t, "GET,POST,DELETE,OPTIONS", resp.Header.Get("Access-Control-Allow-Methods"))
assert.Equal(t, "*", resp.Header.Get("Access-Control-Allow-Origin"))
assert.Equal(t, "https://penguin-stats.io", resp.Header.Get("Access-Control-Allow-Origin"))
assert.Equal(t, "Content-Type,Authorization,X-Requested-With,X-Penguin-Variant,sentry-trace", resp.Header.Get("Access-Control-Allow-Headers"))
assert.Equal(t, "true", resp.Header.Get("Access-Control-Allow-Credentials"))
})
}

0 comments on commit abc2f7b

Please sign in to comment.