make headers thread safe

add reader lock
This commit is contained in:
Saksham Arya 2024-11-20 16:02:55 +05:30
parent e46bd52185
commit c2e744e158
1 changed files with 7 additions and 0 deletions

View File

@ -71,6 +71,9 @@ type Context struct {
// This mutex protects Keys map. // This mutex protects Keys map.
mu sync.RWMutex mu sync.RWMutex
// This mutex protects headers map
hmu sync.RWMutex
// Keys is a key/value pair exclusively for the context of each request. // Keys is a key/value pair exclusively for the context of each request.
Keys map[string]any Keys map[string]any
@ -983,6 +986,8 @@ func (c *Context) Status(code int) {
// It writes a header in the response. // It writes a header in the response.
// If value == "", this method removes the header `c.Writer.Header().Del(key)` // If value == "", this method removes the header `c.Writer.Header().Del(key)`
func (c *Context) Header(key, value string) { func (c *Context) Header(key, value string) {
c.hmu.Lock()
defer c.hmu.Unlock()
if value == "" { if value == "" {
c.Writer.Header().Del(key) c.Writer.Header().Del(key)
return return
@ -992,6 +997,8 @@ func (c *Context) Header(key, value string) {
// GetHeader returns value from request headers. // GetHeader returns value from request headers.
func (c *Context) GetHeader(key string) string { func (c *Context) GetHeader(key string) string {
c.hmu.RLock()
defer c.hmu.RUnlock()
return c.requestHeader(key) return c.requestHeader(key)
} }