https://github.com/gin-contrib/requestid
Request ID middleware for Gin Framework
https://github.com/gin-contrib/requestid
gin gin-gonic gin-middleware middleware
Last synced: over 1 year ago
JSON representation
Request ID middleware for Gin Framework
- Host: GitHub
- URL: https://github.com/gin-contrib/requestid
- Owner: gin-contrib
- License: mit
- Created: 2020-05-03T13:15:56.000Z (about 6 years ago)
- Default Branch: master
- Last Pushed: 2025-03-31T15:07:11.000Z (over 1 year ago)
- Last Synced: 2025-04-01T01:37:35.869Z (over 1 year ago)
- Topics: gin, gin-gonic, gin-middleware, middleware
- Language: Go
- Size: 94.7 KB
- Stars: 224
- Watchers: 5
- Forks: 20
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# RequestID
[](https://github.com/gin-contrib/requestid/actions/workflows/go.yml)
[](https://codecov.io/gh/gin-contrib/requestid)
[](https://goreportcard.com/report/github.com/gin-contrib/requestid)
[](https://godoc.org/github.com/gin-contrib/requestid)
[](https://gitter.im/gin-gonic/gin)
Request ID middleware for Gin Framework. Adds an indentifier to the response using the `X-Request-ID` header. Passes the `X-Request-ID` value back to the caller if it's sent in the request headers.
## Usage
### Start using it
Download and install it.
```sh
go get github.com/gin-contrib/requestid
```
Import it in your code, then use it:
```go
import "github.com/gin-contrib/requestid"
```
## Config
define your custom generator function:
```go
func main() {
r := gin.New()
r.Use(
requestid.New(
requestid.WithGenerator(func() string {
return "test"
}),
requestid.WithCustomHeaderStrKey("your-customer-key"),
),
)
// Example ping request.
r.GET("/ping", func(c *gin.Context) {
c.String(http.StatusOK, "pong "+fmt.Sprint(time.Now().Unix()))
})
// Listen and Server in 0.0.0.0:8080
r.Run(":8080")
}
```
## Example
```go
package main
import (
"fmt"
"net/http"
"time"
"github.com/gin-contrib/requestid"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.New()
r.Use(requestid.New())
// Example ping request.
r.GET("/ping", func(c *gin.Context) {
c.String(http.StatusOK, "pong "+fmt.Sprint(time.Now().Unix()))
})
// Listen and Server in 0.0.0.0:8080
r.Run(":8080")
}
```
How to get the request identifier:
```go
// Example / request.
r.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "id:"+requestid.Get(c))
})
```
You can also get the request identifier from response header:
```sh
> curl -i "http://127.0.0.1:8080"
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
X-Request-ID: 77966910-3912-4193-9b74-267491c51700
Content-Length: 39
id:77966910-3912-4193-9b74-267491c51700
```
When http request with custom identifier, gin server return the custom identifier in response header.
```sh
> curl -i -H "X-Request-ID:test" "http://127.0.0.1:8080"
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
X-Request-Id: test
Content-Length: 13
id:test
```