Skip to content

Commit

Permalink
new CORSMiddleware test
Browse files Browse the repository at this point in the history
  • Loading branch information
chenghb911 committed Nov 6, 2023
1 parent 4abd8c2 commit 6c2e034
Showing 1 changed file with 43 additions and 9 deletions.
52 changes: 43 additions & 9 deletions network/http/gin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@
package http

import (
"github.com/stretchr/testify/assert"
"io"
"net/http"
"strings"
"testing"
"time"

Expand All @@ -31,11 +33,23 @@ func BenchmarkAllMiddlewares(b *testing.B) {
},
},
{
name: "cors",
name: "cors-0",
ms: []gin.HandlerFunc{
CORSMiddleware([]string{}),
},
},
{
name: "cors-1",
ms: []gin.HandlerFunc{
CORSMiddleware([]string{"http://foobar.com"}),
},
},
{
name: "cors-2",
ms: []gin.HandlerFunc{
CORSMiddleware([]string{"www.baidu.com"}),
},
},
{
name: "trace-id",
ms: []gin.HandlerFunc{
Expand Down Expand Up @@ -79,14 +93,34 @@ func BenchmarkAllMiddlewares(b *testing.B) {
time.Sleep(time.Second)

for i := 0; i < b.N; i++ {
resp, err := http.Get("http://localhost:1234/v1/get")
if err != nil {
b.Logf("get error: %s, ignored", err)
}

if resp.Body != nil {
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
if !strings.Contains(bc.name, "cors") {
resp, err := http.Get("http://localhost:1234/v1/get")
if err != nil {
b.Logf("get error: %s, ignored", err)
}

if resp.Body != nil {
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
}
} else {
req, err := http.NewRequest("GET", "http://localhost:1234/v1/get", nil)
if err != nil {
b.Error(err)
}
origin := "http://foobar.com"
req.Header.Set("Origin", origin)
c := &http.Client{}
resp, err := c.Do(req)
if err != nil {
b.Error(err)
}
defer resp.Body.Close()
got := resp.Header.Get("Access-Control-Allow-Origin")
if bc.name == "cors-2" {
origin = ""
}
assert.Equal(b, origin, got, "expect %s, got '%s'", origin, got)
}
}
srv.Close()
Expand Down

0 comments on commit 6c2e034

Please sign in to comment.