https://github.com/bsm/conditional
Conditional HTTP responses with Go
https://github.com/bsm/conditional
Last synced: about 1 year ago
JSON representation
Conditional HTTP responses with Go
- Host: GitHub
- URL: https://github.com/bsm/conditional
- Owner: bsm
- License: other
- Created: 2020-02-12T17:14:09.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2020-02-27T13:49:00.000Z (over 6 years ago)
- Last Synced: 2025-04-13T05:54:50.606Z (about 1 year ago)
- Language: Go
- Size: 9.77 KB
- Stars: 0
- Watchers: 2
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Conditional
[](https://travis-ci.org/bsm/conditional)
[](http://godoc.org/github.com/bsm/conditional)
[](https://goreportcard.com/report/github.com/bsm/conditional)
[](https://opensource.org/licenses/Apache-2.0)
Conditional HTTP helpers for [Go](https://golang.org) stdlib's [net/http](https://golang.org/pkg/net/http) package.
Supported headers:
* `If-Match`
* `If-None-Match`
* `If-Modified-Since`
* `If-Unmodified-Since`
## Example:
```go
import(
"fmt"
"net/http"
"net/http/httptest"
"github.com/bsm/conditional"
)
func main() {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// set ETag and/or Last-Modified headers
w.Header().Set("ETag", `"strong"`)
w.Header().Set("Last-Modified", "Fri, 05 Jan 2018 11:25:15 GMT")
// perform conditional check
if conditional.Check(w, r) {
return
}
w.WriteHeader(http.StatusNoContent)
}))
defer srv.Close()
client := new(http.Client)
// make a plain GET request
req, err := http.NewRequest("GET", srv.URL, nil)
if err != nil {
panic(err)
}
res, err := client.Do(req)
if err != nil {
panic(err)
}
fmt.Println(res.Status) // => 204 No Content
// now, try it with a matchingg "If-Modified-Since"
req, err = http.NewRequest("GET", srv.URL, nil)
if err != nil {
panic(err)
}
req.Header.Set("If-Modified-Since", "Fri, 05 Jan 2018 11:25:15 GMT")
res, err = client.Do(req)
if err != nil {
panic(err)
}
fmt.Println(res.Status) // => 304 Not Modified
}
```