-
Notifications
You must be signed in to change notification settings - Fork 53
/
grpc.go
60 lines (51 loc) · 1.15 KB
/
grpc.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
package util
import (
"bytes"
"errors"
"fmt"
"github.com/zeebo/xxh3"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type ServicePackInterface interface {
Unpack() (*grpc.ServiceDesc, any)
}
type ServicePack[T any] struct {
desc *grpc.ServiceDesc
impl T
}
func (s ServicePack[T]) Unpack() (*grpc.ServiceDesc, any) {
return s.desc, s.impl
}
func PackService[T any](desc *grpc.ServiceDesc, impl T) ServicePack[T] {
return ServicePack[T]{
desc: desc,
impl: impl,
}
}
func StatusError(code codes.Code) error {
return status.Error(code, code.String())
}
// Like status.Code(), but supports wrapped errors.
func StatusCode(err error) codes.Code {
if err == nil {
return codes.OK
}
var grpcStatus interface{ GRPCStatus() *status.Status }
code := codes.Unknown
if errors.As(err, &grpcStatus) {
code = grpcStatus.GRPCStatus().Code()
}
return code
}
func HashStrings(strings []string) string {
var buf bytes.Buffer
for _, s := range strings {
buf.WriteString(fmt.Sprintf("%s-", s))
}
return fmt.Sprintf("%d", HashString(buf.String()))
}
func HashString(s string) uint64 {
return xxh3.HashString(s)
}