Debian Codegraph @

pkg/objectstorage/filestore/file.go

raw
1 // Copyright 2022 The Archivista Contributors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package filestore
16
17 import (
18 "context"
19 "io"
20 "log"
21 "net/http"
22 "os"
23 "path/filepath"
24 "time"
25
26 "github.com/gorilla/handlers"
27 )
28
29 type Store struct {
30 prefix string
31 }
32
33 func New(ctx context.Context, directory string, address string) (*Store, <-chan error, error) {
34 errCh := make(chan error)
35 go func() {
36 server := &http.Server{
37 Addr: address,
38 Handler: handlers.CompressHandler(http.FileServer(http.Dir(directory))),
39 ReadTimeout: 5 * time.Second,
40 WriteTimeout: 10 * time.Second,
41 }
42
43 if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
44 log.Fatalf("Could not listen on %s: %v\n", address, err)
45 }
46
47 <-ctx.Done()
48
49 if err := server.Shutdown(context.Background()); err != nil {
50 log.Fatalf("Server Shutdown Failed:%+v", err)
51 }
52
53 close(errCh)
54 }()
55
56 return &Store{
57 prefix: directory,
58 }, errCh, nil
59 }
60
61 func (s *Store) Get(ctx context.Context, gitoid string) (io.ReadCloser, error) {
62 if filepath.IsLocal(gitoid) {
63 return os.Open(filepath.Join(s.prefix, gitoid+".json"))
64 } else {
65 return nil, filepath.ErrBadPattern
66 }
67 }
68
69 func (s *Store) Store(ctx context.Context, gitoid string, payload []byte) error {
70 if filepath.IsLocal(gitoid) {
71 return os.WriteFile(filepath.Join(s.prefix, gitoid+".json"), payload, 0o600)
72 } else {
73 return filepath.ErrBadPattern
74 }
75 }