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 }