Compare commits

...

3 Commits

Author SHA1 Message Date
Saksham Arya a9ea3b4b00
Merge 4857f7c66e into e46bd52185 2024-11-20 18:54:01 +05:30
Saksham Arya 4857f7c66e add test case
fix lint
2024-11-20 18:53:35 +05:30
Saksham Arya 98499b58e0 make headers thread safe
add reader lock
2024-11-20 16:18:58 +05:30
2 changed files with 30 additions and 4 deletions

View File

@ -21,6 +21,7 @@ import (
"time"
"github.com/gin-contrib/sse"
"github.com/gin-gonic/gin/binding"
"github.com/gin-gonic/gin/render"
)
@ -983,6 +984,8 @@ func (c *Context) Status(code int) {
// It writes a header in the response.
// If value == "", this method removes the header `c.Writer.Header().Del(key)`
func (c *Context) Header(key, value string) {
c.mu.Lock()
defer c.mu.Unlock()
if value == "" {
c.Writer.Header().Del(key)
return
@ -992,6 +995,8 @@ func (c *Context) Header(key, value string) {
// GetHeader returns value from request headers.
func (c *Context) GetHeader(key string) string {
c.mu.RLock()
defer c.mu.RUnlock()
return c.requestHeader(key)
}

View File

@ -27,11 +27,12 @@ import (
"time"
"github.com/gin-contrib/sse"
"github.com/gin-gonic/gin/binding"
testdata "github.com/gin-gonic/gin/testdata/protoexample"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/proto"
"github.com/gin-gonic/gin/binding"
testdata "github.com/gin-gonic/gin/testdata/protoexample"
)
var _ context.Context = (*Context)(nil)
@ -166,7 +167,7 @@ func TestSaveUploadedFileWithPermission(t *testing.T) {
require.NoError(t, err)
mw.Close()
c, _ := CreateTestContext(httptest.NewRecorder())
c.Request, _ = http.NewRequest("POST", "/", buf)
c.Request, _ = http.NewRequest(http.MethodPost, "/", buf)
c.Request.Header.Set("Content-Type", mw.FormDataContentType())
f, err := c.FormFile("file")
require.NoError(t, err)
@ -187,7 +188,7 @@ func TestSaveUploadedFileWithPermissionFailed(t *testing.T) {
require.NoError(t, err)
mw.Close()
c, _ := CreateTestContext(httptest.NewRecorder())
c.Request, _ = http.NewRequest("POST", "/", buf)
c.Request, _ = http.NewRequest(http.MethodPost, "/", buf)
c.Request.Header.Set("Content-Type", mw.FormDataContentType())
f, err := c.FormFile("file")
require.NoError(t, err)
@ -3123,3 +3124,23 @@ func TestContextNext(t *testing.T) {
assert.True(t, exists)
assert.Equal(t, "value3", value)
}
func TestParallelHeaderWrite(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < 1000; i++ {
c.Header("key", "value")
}
}()
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < 1000; i++ {
c.Header("key", "value")
}
}()
wg.Wait()
}