golang.org/x/playground@v0.0.0-20230418134305-14ebe15bcd59/store.go (about)

     1  // Copyright 2017 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package main
     6  
     7  import (
     8  	"context"
     9  	"sync"
    10  
    11  	"cloud.google.com/go/datastore"
    12  )
    13  
    14  type store interface {
    15  	PutSnippet(ctx context.Context, id string, snip *snippet) error
    16  	GetSnippet(ctx context.Context, id string, snip *snippet) error
    17  }
    18  
    19  type cloudDatastore struct {
    20  	client *datastore.Client
    21  }
    22  
    23  func (s cloudDatastore) PutSnippet(ctx context.Context, id string, snip *snippet) error {
    24  	key := datastore.NameKey("Snippet", id, nil)
    25  	_, err := s.client.Put(ctx, key, snip)
    26  	return err
    27  }
    28  
    29  func (s cloudDatastore) GetSnippet(ctx context.Context, id string, snip *snippet) error {
    30  	key := datastore.NameKey("Snippet", id, nil)
    31  	return s.client.Get(ctx, key, snip)
    32  }
    33  
    34  // inMemStore is a store backed by a map that should only be used for testing.
    35  type inMemStore struct {
    36  	sync.RWMutex
    37  	m map[string]*snippet // key -> snippet
    38  }
    39  
    40  func (s *inMemStore) PutSnippet(_ context.Context, id string, snip *snippet) error {
    41  	s.Lock()
    42  	if s.m == nil {
    43  		s.m = map[string]*snippet{}
    44  	}
    45  	b := make([]byte, len(snip.Body))
    46  	copy(b, snip.Body)
    47  	s.m[id] = &snippet{Body: b}
    48  	s.Unlock()
    49  	return nil
    50  }
    51  
    52  func (s *inMemStore) GetSnippet(_ context.Context, id string, snip *snippet) error {
    53  	s.RLock()
    54  	defer s.RUnlock()
    55  	v, ok := s.m[id]
    56  	if !ok {
    57  		return datastore.ErrNoSuchEntity
    58  	}
    59  	*snip = *v
    60  	return nil
    61  }