PageRenderTime 21ms CodeModel.GetById 9ms app.highlight 7ms RepoModel.GetById 2ms app.codeStats 0ms

/cache/file.go

http://github.com/petar/GoHTTP
Go | 56 lines | 43 code | 8 blank | 5 comment | 9 complexity | 5d65ce9b2c4de36adb16d42118e323d3 MD5 | raw file
 1// Copyright 2011 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
 5package cache
 6
 7import (
 8	"io/ioutil"
 9	"os"
10	"sync"
11)
12
13// CachedFile is responsible for returning the contents of a single file.
14// It remembers the contents in memory, and updates it as necessary.
15type CachedFile struct {
16	sync.Mutex
17	fname string
18	data  []byte
19	mtime int64
20}
21
22func NewCachedFile(filename string) *CachedFile {
23	return &CachedFile{fname: filename}
24}
25
26func (c *CachedFile) Get() (data []byte, err error) {
27	c.Lock()
28	defer c.Unlock()
29
30	if c.data == nil {
31		return c.readFile()
32	}
33	fi, err := os.Stat(c.fname)
34	if err != nil {
35		return nil, err
36	}
37	if fi.ModTime().UnixNano() > c.mtime {
38		return c.readFile()
39	}
40	return c.data, nil
41}
42
43func (c *CachedFile) readFile() (data []byte, err error) {
44	fi, err := os.Stat(c.fname)
45	if err != nil {
46		return nil, err
47	}
48	data, err = ioutil.ReadFile(c.fname)
49	if err != nil {
50		return nil, err
51	}
52	c.data = data
53	c.mtime = fi.ModTime().UnixNano()
54
55	return data, nil
56}