-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgcache.go
36 lines (30 loc) · 949 Bytes
/
gcache.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
package gcache
import (
"context"
"fmt"
"log/slog"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
// ErrKey specifies the error key for logging.
var ErrKey = "error"
// ETag returns the ETag from the context.
func ETag(ctx context.Context) string {
if md, ok := metadata.FromIncomingContext(ctx); ok {
if h := md.Get("If-None-Match"); len(h) > 0 {
return h[0]
}
}
return ""
}
// NotChanged responds to the client with codes.Aborted and the etag,
// meaning that the client should use the cached value.
func NotChanged(ctx context.Context, etag string) error {
if err := grpc.SetHeader(ctx, metadata.Pairs("ETag", etag)); err != nil {
slog.WarnContext(ctx, "gcache: failed to set ETag header", slog.Any(ErrKey, err))
return fmt.Errorf("gcache: failed to set ETag header: %w", err)
}
return status.Error(codes.Aborted, "gcache: not changed")
}