Skip to content

Commit

Permalink
refactro: support private cache function
Browse files Browse the repository at this point in the history
  • Loading branch information
vicanso committed Mar 19, 2021
1 parent 02c303e commit 2be2007
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
11 changes: 8 additions & 3 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -571,17 +571,17 @@ func (c *Context) NotModified() {
c.StatusCode = http.StatusNotModified
}

// NoCache set `Cache-Control: no-cache` to the http response header
// NoCache sets `Cache-Control: no-cache` to the http response header
func (c *Context) NoCache() {
c.SetHeader(HeaderCacheControl, "no-cache")
}

// NoStore set `Cache-Control: no-store` to the http response header
// NoStore sets `Cache-Control: no-store` to the http response header
func (c *Context) NoStore() {
c.SetHeader(HeaderCacheControl, "no-store")
}

// CacheMaxAge set `Cache-Control: public, max-age=MaxAge, s-maxage=SMaxAge` to the http response header.
// CacheMaxAge sets `Cache-Control: public, max-age=MaxAge, s-maxage=SMaxAge` to the http response header.
// If args is not empty, it will use the first duration as SMaxAge
func (c *Context) CacheMaxAge(age time.Duration, args ...time.Duration) {
cache := fmt.Sprintf("public, max-age=%d", int(age.Seconds()))
Expand All @@ -592,6 +592,11 @@ func (c *Context) CacheMaxAge(age time.Duration, args ...time.Duration) {
c.SetHeader(HeaderCacheControl, cache)
}

// PrivateCacheMaxAge sets `Cache-Control: private, max-age=MaxAge` to the response header.
func (c *Context) PrivateCacheMaxAge(age time.Duration) {
c.SetHeader(HeaderCacheControl, fmt.Sprintf("private, max-age=%d", int(age.Seconds())))
}

// Created sets the body to response and set the status to 201
func (c *Context) Created(body interface{}) {
c.StatusCode = http.StatusCreated
Expand Down
10 changes: 10 additions & 0 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -627,6 +627,16 @@ func TestCacheControl(t *testing.T) {
},
cacheControl: "public, max-age=60, s-maxage=10",
},
// private max-age
{
newContext: func() *Context {
resp := httptest.NewRecorder()
c := NewContext(resp, nil)
c.PrivateCacheMaxAge(time.Minute)
return c
},
cacheControl: "private, max-age=60",
},
}

for _, tt := range tests {
Expand Down

0 comments on commit 2be2007

Please sign in to comment.