This repository has been archived by the owner on Apr 26, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
in_memory_resource.go
68 lines (60 loc) · 1.84 KB
/
in_memory_resource.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
62
63
64
65
66
67
68
package server
import (
"bytes"
"compress/flate"
"fmt"
"mime"
"path/filepath"
)
// ResourceType specifies the content type of the resource
type ResourceType = string
// Compression specifies the content compression type
type Compression = string
// CompressionDeflate compressionType deflate
const CompressionDeflate = "deflate"
// InMemoryResource hold the resouce that can be served by the server
type InMemoryResource struct {
Name string
Type ResourceType
CompressionType Compression
Size int
InitialSize int
Content []byte
}
// NewInMemoryResource method will initialize a new InMemoryResource object and return it
func NewInMemoryResource(name string, content []byte) (InMemoryResource, error) {
compressedContent, err := compressResource(content)
if err != nil {
return InMemoryResource{}, err
}
return InMemoryResource{
Name: name,
InitialSize: len(content),
Size: len(compressedContent),
Content: compressedContent,
Type: mime.TypeByExtension(filepath.Ext(name)),
CompressionType: CompressionDeflate,
}, nil
}
// String method will genereate a string representation of the InMemoryResource object
func (resource *InMemoryResource) String() string {
return fmt.Sprintf("{ name: '%s', size: %d, initial-size: %d, contentType: '%s', compressionType: '%s' }",
resource.Name,
resource.Size,
resource.InitialSize,
resource.Type,
resource.CompressionType,
)
}
// compressResource receives a []byte with the resource content and returns a compressed version
func compressResource(content []byte) ([]byte, error) {
w := new(bytes.Buffer)
flateWriter, _ := flate.NewWriter(w, flate.BestCompression)
defer flateWriter.Close()
_, err := flateWriter.Write(content)
flateWriter.Flush()
if err != nil {
return nil, err
}
return w.Bytes(), nil
}