-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
71 lines (60 loc) · 1.35 KB
/
utils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package main
import (
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
"github.com/nu7hatch/gouuid"
"golang.org/x/net/context"
metadata "google.golang.org/grpc/metadata"
)
// TODO(labkode) set collation for table and column to utf8. The default is swedish
type record struct {
ID string
Path string `sql:"unique_index:idx_path"`
Checksum string
ETag string
MTime uint32
}
func (r *record) String() string {
return fmt.Sprintf("id=%s path=%s sum=%s etag=%s mtime=%d",
r.ID, r.Path, r.Checksum, r.ETag, r.MTime)
}
func newDB(driver, dsn string) (*gorm.DB, error) {
db, err := gorm.Open(driver, dsn)
if err != nil {
return nil, err
}
db.AutoMigrate(&record{})
return &db, nil
}
func newGRPCTraceContext(ctx context.Context, trace string) context.Context {
md := metadata.Pairs("trace", trace)
ctx = metadata.NewContext(ctx, md)
return ctx
}
func getGRPCTraceID(ctx context.Context) (string, error) {
md, ok := metadata.FromContext(ctx)
if !ok {
id, err := uuid.NewV4()
if err != nil {
return "", err
}
return id.String(), nil
}
tokens := md["trace"]
if len(tokens) == 0 {
id, err := uuid.NewV4()
if err != nil {
return "", err
}
return id.String(), nil
}
if tokens[0] != "" {
return tokens[0], nil
}
id, err := uuid.NewV4()
if err != nil {
return "", err
}
return id.String(), nil
}