This repository has been archived by the owner on Apr 23, 2023. It is now read-only.
forked from golang/playground
-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.go
61 lines (51 loc) · 1.41 KB
/
store.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
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"context"
"sync"
"cloud.google.com/go/datastore"
)
type store interface {
PutSnippet(ctx context.Context, id string, snip *snippet) error
GetSnippet(ctx context.Context, id string, snip *snippet) error
}
type cloudDatastore struct {
client *datastore.Client
}
func (s cloudDatastore) PutSnippet(ctx context.Context, id string, snip *snippet) error {
key := datastore.NameKey("Snippet", id, nil)
_, err := s.client.Put(ctx, key, snip)
return err
}
func (s cloudDatastore) GetSnippet(ctx context.Context, id string, snip *snippet) error {
key := datastore.NameKey("Snippet", id, nil)
return s.client.Get(ctx, key, snip)
}
// inMemStore is a store backed by a map that should only be used for testing.
type inMemStore struct {
sync.RWMutex
m map[string]*snippet // key -> snippet
}
func (s *inMemStore) PutSnippet(_ context.Context, id string, snip *snippet) error {
s.Lock()
if s.m == nil {
s.m = map[string]*snippet{}
}
b := make([]byte, len(snip.Body))
copy(b, snip.Body)
s.m[id] = &snippet{Body: b}
s.Unlock()
return nil
}
func (s *inMemStore) GetSnippet(_ context.Context, id string, snip *snippet) error {
s.RLock()
defer s.RUnlock()
v, ok := s.m[id]
if !ok {
return datastore.ErrNoSuchEntity
}
*snip = *v
return nil
}