GOPackageHeaderServer/web/utils/partial-range-writer.go
Captain ALM 0d4036d05c
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/tag Build is passing
Refactor and add cache and range support.
2022-07-12 15:41:50 +01:00

48 lines
1.4 KiB
Go

package utils
import "io"
func NewPartialRangeWriter(writerIn io.Writer, httpRangeIn ContentRangeValue) io.Writer {
return &PartialRangeWriter{
passedWriter: writerIn,
passedWriterIndex: 0,
httpRange: httpRangeIn,
exclusiveLastIndex: httpRangeIn.Start + httpRangeIn.Length,
}
}
type PartialRangeWriter struct {
passedWriter io.Writer
passedWriterIndex int64
exclusiveLastIndex int64
httpRange ContentRangeValue
}
func (prw *PartialRangeWriter) Write(p []byte) (n int, err error) {
var pOffsetIndex int64 = -1
if prw.passedWriterIndex >= prw.httpRange.Start && prw.passedWriterIndex < prw.exclusiveLastIndex {
pOffsetIndex = 0
} else if prw.passedWriterIndex+int64(len(p)) > prw.httpRange.Start && prw.passedWriterIndex < prw.exclusiveLastIndex {
pOffsetIndex = prw.httpRange.Start - prw.passedWriterIndex
prw.passedWriterIndex += pOffsetIndex
} else {
prw.passedWriterIndex += int64(len(p))
}
if pOffsetIndex >= 0 {
if prw.passedWriterIndex+(int64(len(p))-pOffsetIndex) <= prw.exclusiveLastIndex {
written, err := prw.passedWriter.Write(p[pOffsetIndex:])
prw.passedWriterIndex += int64(written)
if err != nil {
return written, err
}
} else {
written, err := prw.passedWriter.Write(p[pOffsetIndex : prw.exclusiveLastIndex-prw.passedWriterIndex+pOffsetIndex])
prw.passedWriterIndex += int64(written)
if err != nil {
return written, err
}
}
}
return n, nil
}