mirror of
https://gitee.com/dromara/mayfly-go
synced 2026-05-10 21:15:19 +08:00
feat: 新增统一文件模块,统一文件操作
This commit is contained in:
26
server/pkg/utils/writerx/counting_writer.go
Normal file
26
server/pkg/utils/writerx/counting_writer.go
Normal file
@@ -0,0 +1,26 @@
|
||||
package writerx
|
||||
|
||||
import "io"
|
||||
|
||||
type CountingWriteCloser struct {
|
||||
w io.WriteCloser
|
||||
n int64 // 已写入的字节数
|
||||
}
|
||||
|
||||
func (c *CountingWriteCloser) Write(p []byte) (int, error) {
|
||||
n, err := c.w.Write(p)
|
||||
c.n += int64(n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (c *CountingWriteCloser) Close() error {
|
||||
return c.w.Close()
|
||||
}
|
||||
|
||||
func (c *CountingWriteCloser) BytesWritten() int64 {
|
||||
return c.n
|
||||
}
|
||||
|
||||
func NewCountingWriteCloser(writer io.WriteCloser) *CountingWriteCloser {
|
||||
return &CountingWriteCloser{w: writer}
|
||||
}
|
||||
50
server/pkg/utils/writerx/gzip_writer.go
Normal file
50
server/pkg/utils/writerx/gzip_writer.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package writerx
|
||||
|
||||
import (
|
||||
"compress/gzip"
|
||||
"io"
|
||||
"mayfly-go/pkg/biz"
|
||||
)
|
||||
|
||||
type GzipWriter struct {
|
||||
tryFlushCount int
|
||||
writer *gzip.Writer
|
||||
aborted bool
|
||||
}
|
||||
|
||||
func NewGzipWriter(writer io.Writer) *GzipWriter {
|
||||
return &GzipWriter{writer: gzip.NewWriter(writer)}
|
||||
}
|
||||
|
||||
func (g *GzipWriter) WriteString(data string) {
|
||||
if g.aborted {
|
||||
return
|
||||
}
|
||||
if _, err := g.writer.Write([]byte(data)); err != nil {
|
||||
g.aborted = true
|
||||
biz.IsTrue(false, "数据库导出失败:%s", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (g *GzipWriter) Write(p []byte) (n int, err error) {
|
||||
if g.aborted {
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := g.writer.Write(p); err != nil {
|
||||
g.aborted = true
|
||||
biz.IsTrue(false, "数据库导出失败:%s", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (g *GzipWriter) Close() error {
|
||||
return g.writer.Close()
|
||||
}
|
||||
|
||||
func (g *GzipWriter) TryFlush() {
|
||||
if g.tryFlushCount%1000 == 0 {
|
||||
g.writer.Flush()
|
||||
}
|
||||
g.tryFlushCount += 1
|
||||
}
|
||||
21
server/pkg/utils/writerx/string_writer.go
Normal file
21
server/pkg/utils/writerx/string_writer.go
Normal file
@@ -0,0 +1,21 @@
|
||||
package writerx
|
||||
|
||||
import (
|
||||
"io"
|
||||
)
|
||||
|
||||
type StringWriter struct {
|
||||
io.WriteCloser
|
||||
}
|
||||
|
||||
func (sw *StringWriter) WriteString(s string) (n int, err error) {
|
||||
return sw.WriteCloser.Write([]byte(s))
|
||||
}
|
||||
|
||||
func (sw *StringWriter) Close() error {
|
||||
return sw.WriteCloser.Close()
|
||||
}
|
||||
|
||||
func NewStringWriter(writer io.WriteCloser) *StringWriter {
|
||||
return &StringWriter{WriteCloser: writer}
|
||||
}
|
||||
Reference in New Issue
Block a user