write.go 1.34 KB
Newer Older
“李磊”'s avatar
“李磊” committed
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
package file

import (
	"bytes"
	"errors"
	"io"
	"io/ioutil"
	"os"

	"linkfog.com/public/lib/file/config"
	log "linkfog.com/public/lib/l"
	"linkfog.com/public/pkg/ratelimit"
)

// errInvalidWrite means that a write returned an impossible count.
var errInvalidWrite = errors.New("invalid write result")

func WriteFile(name string, data []byte, perm os.FileMode) error {
	if !config.EnableRateLimitBucket() {
		log.Debug("write file no rate limit.")
		err := ioutil.WriteFile(name, data, perm)
		if err != nil {
			return log.WrapError("no rate limit write file err:")
		}
		return err
	}
	f, err := os.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
	if err != nil {
		return log.WrapError("write file with rateLimit open file err:", err)
	}
	defer f.Close()
	// ratelimit.NewBucket(1000*time.Nanosecond, 1*1024*1024)
	rateWriter := ratelimit.Writer(f, config.RateLimitBucket())
	bytesReader := bytes.NewReader(data)

	for {
		dateByte := make([]byte, config.RateLimitBucket().Capacity())
		_, err := bytesReader.Read(dateByte)
		if err != nil {
			if err != io.EOF {
				return log.WrapError("write file with rateLimit read data err:", err)
			}
			break
		}

		_, err = rateWriter.Write(dateByte)
		if err != nil {
			return log.WrapError("write file with rateLimit write data err:", err)
		}
	}

	return err
}