projects
/
arvados.git
/ blobdiff
summary
|
shortlog
|
log
|
commit
|
commitdiff
|
tree
raw
|
inline
| side by side
Merge branch '17022-user-activity-report' refs #17022
[arvados.git]
/
sdk
/
go
/
httpserver
/
id_generator.go
diff --git
a/sdk/go/httpserver/id_generator.go
b/sdk/go/httpserver/id_generator.go
index c744691aa83cc325c9edc5ec2465b68320b687dc..14d89873b60f7d902a39a6b337eea78e8040d0c3 100644
(file)
--- a/
sdk/go/httpserver/id_generator.go
+++ b/
sdk/go/httpserver/id_generator.go
@@
-5,12
+5,17
@@
package httpserver
import (
package httpserver
import (
+ "math/rand"
"net/http"
"strconv"
"sync"
"time"
)
"net/http"
"strconv"
"sync"
"time"
)
+const (
+ HeaderRequestID = "X-Request-Id"
+)
+
// IDGenerator generates alphanumeric strings suitable for use as
// unique IDs (a given IDGenerator will never return the same ID
// twice).
// IDGenerator generates alphanumeric strings suitable for use as
// unique IDs (a given IDGenerator will never return the same ID
// twice).
@@
-18,21
+23,24
@@
type IDGenerator struct {
// Prefix is prepended to each returned ID.
Prefix string
// Prefix is prepended to each returned ID.
Prefix string
- lastID int64
- mtx sync.Mutex
+ mtx sync.Mutex
+ src rand.Source
}
// Next returns a new ID string. It is safe to call Next from multiple
// goroutines.
func (g *IDGenerator) Next() string {
}
// Next returns a new ID string. It is safe to call Next from multiple
// goroutines.
func (g *IDGenerator) Next() string {
- id := time.Now().UnixNano()
g.mtx.Lock()
g.mtx.Lock()
- if id <= g.lastID {
- id = g.lastID + 1
+ defer g.mtx.Unlock()
+ if g.src == nil {
+ g.src = rand.NewSource(time.Now().UnixNano())
+ }
+ a, b := g.src.Int63(), g.src.Int63()
+ id := strconv.FormatInt(a, 36) + strconv.FormatInt(b, 36)
+ for len(id) > 20 {
+ id = id[:20]
}
}
- g.lastID = id
- g.mtx.Unlock()
- return g.Prefix + strconv.FormatInt(id, 36)
+ return g.Prefix + id
}
// AddRequestIDs wraps an http.Handler, adding an X-Request-Id header
}
// AddRequestIDs wraps an http.Handler, adding an X-Request-Id header
@@
-40,8
+48,11
@@
func (g *IDGenerator) Next() string {
func AddRequestIDs(h http.Handler) http.Handler {
gen := &IDGenerator{Prefix: "req-"}
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
func AddRequestIDs(h http.Handler) http.Handler {
gen := &IDGenerator{Prefix: "req-"}
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
- if req.Header.Get("X-Request-Id") == "" {
- req.Header.Set("X-Request-Id", gen.Next())
+ if req.Header.Get(HeaderRequestID) == "" {
+ if req.Header == nil {
+ req.Header = http.Header{}
+ }
+ req.Header.Set(HeaderRequestID, gen.Next())
}
h.ServeHTTP(w, req)
})
}
h.ServeHTTP(w, req)
})