golifehk/utils/cache.go

69 lines
1.4 KiB
Go
Raw Normal View History

2022-09-14 09:12:48 +00:00
package utils
import (
"bytes"
"io"
2022-09-14 14:54:51 +00:00
"log"
2022-09-14 09:12:48 +00:00
"os"
"path/filepath"
"time"
)
func CacheStream( path string, readStream func() ( io.ReadCloser, error ), expires int ) ( *bytes.Buffer, error ) {
cache, err := os.Stat( path )
// Check if cache exists and not expired
if err == nil {
expired := cache.ModTime().Add( 60 * 1e9 )
if time.Now().Before( expired ) {
f, err := os.Open( path )
if err == nil {
defer f.Close()
2022-09-14 14:54:51 +00:00
log.Printf( "Using cache: %s", path )
2022-09-14 09:12:48 +00:00
writeBuff := bytes.NewBuffer( []byte{} )
_, err = io.Copy( writeBuff, f )
if err == nil {
return writeBuff, nil
}
}
}
}
err = os.MkdirAll( filepath.Dir( path ), 0750 )
if err != nil {
return nil, err
}
writeBuff := bytes.NewBuffer( []byte{} )
// Get the reader that return new data
s, err := readStream()
if err != nil {
return nil, err
}
defer s.Close()
_, err = io.Copy( writeBuff, s )
if err != nil {
return nil, err
}
f, err := os.OpenFile( path, os.O_CREATE | os.O_WRONLY | os.O_TRUNC, 0644 )
if err != nil {
return nil, err
}
defer f.Close()
data := writeBuff.Bytes()
_, err = io.Copy( f, bytes.NewReader( data ) )
if err != nil {
return nil, err
}
return writeBuff, nil
}