https://github.com/kataras/requestid
Unique Identifier for each HTTP request
https://github.com/kataras/requestid
go golang http iris requestid unique-identifier
Last synced: 10 months ago
JSON representation
Unique Identifier for each HTTP request
- Host: GitHub
- URL: https://github.com/kataras/requestid
- Owner: kataras
- License: mit
- Created: 2020-07-12T14:43:15.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2023-10-26T21:55:54.000Z (over 2 years ago)
- Last Synced: 2025-03-25T01:51:13.287Z (10 months ago)
- Topics: go, golang, http, iris, requestid, unique-identifier
- Language: Go
- Homepage:
- Size: 15.6 KB
- Stars: 6
- Watchers: 2
- Forks: 2
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- Contributing: CONTRIBUTING.md
- Funding: .github/FUNDING.yml
- License: LICENSE
- Code of conduct: CODE_OF_CONDUCT.md
Awesome Lists containing this project
README
# Request ID
[](https://github.com/kataras/requestid/actions) [](https://goreportcard.com/report/github.com/kataras/requestid) [](https://godoc.org/github.com/kataras/requestid)
Unique Identifier for each HTTP request. Useful for logging, propagation and e.t.c.
## Installation
The only requirement is the [Go Programming Language](https://golang.org/dl).
```sh
$ go get github.com/kataras/requestid
```
## Getting Started
Import the package:
```go
package main
import "github.com/kataras/requestid"
```
Wrap a handler with the `Handler` function and retrieve the request ID using the `Get` function:
```go
import "net/http"
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request){
id:= requestid.Get(r)
w.Write([]byte(id))
})
http.ListenAndServe(":8080", requestid.Handler(mux))
}
```
By-default the `requestid` middleware uses the `X-Request-Id` header to extract and set the request ID.
It generates a [universally unique identifier](https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_(random)) when the request header is missing. Use custom logic to extract and set the request ID using `HandlerWithGenerator`:
```go
import "net/http"
func main() {
// extract from a request header and set to the response header.
gen := func(w http.ResponseWriter, r *http.Request) string {
id:= r.Header.Get("X-Custom-Id")
if id == "" {
// [custom logic to generate ID...]
}
w.Header().Set("X-Custom-Id", id)
return id
}
// [...]
router := requestid.HandlerWithGenerator(mux, gen)
http.ListenAndServe(":8080", router)
}
```
When you want an identifier of request based on the headers, body and e.t.c. use the `HashGenerator` helper. Note that, the request id will be the same if the same client sends the same requests (that's the goal here):
```go
func main() {
// [...]
includeBodyOnHash := false
gen := requestid.HashGenerator(includeBodyOnHash)
requestid.HandlerWithGenerator(mux, gen)
// [...]
}
```
## License
This software is licensed under the [MIT License](LICENSE).