github.com/TeaOSLab/EdgeNode@v1.3.8/internal/utils/readers/reader_closer_byte_ranges_test.go (about)

     1  // Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
     2  
     3  package readers_test
     4  
     5  import (
     6  	"bytes"
     7  	"fmt"
     8  	"github.com/TeaOSLab/EdgeNode/internal/utils/readers"
     9  	"io"
    10  	"net/textproto"
    11  	"testing"
    12  )
    13  
    14  func TestNewByteRangesReader(t *testing.T) {
    15  	var boundary = "7143cd51d2ee12a1"
    16  	var dashBoundary = "--" + boundary
    17  	var b = bytes.NewReader([]byte(dashBoundary + "\r\nContent-Range: bytes 0-4/36\r\nContent-Type: text/plain\r\n\r\n01234\r\n" + dashBoundary + "\r\nContent-Range: bytes 5-9/36\r\nContent-Type: text/plain\r\n\r\n56789\r\n--" + boundary + "\r\nContent-Range: bytes 10-12/36\r\nContent-Type: text/plain\r\n\r\nabc\r\n" + dashBoundary + "--\r\n"))
    18  
    19  	var reader = readers.NewByteRangesReaderCloser(io.NopCloser(b), boundary)
    20  	var p = make([]byte, 16)
    21  	for {
    22  		n, err := reader.Read(p)
    23  		if n > 0 {
    24  			fmt.Print(string(p[:n]))
    25  		}
    26  		if err != nil {
    27  			if err != io.EOF {
    28  				t.Fatal(err)
    29  			}
    30  			break
    31  		}
    32  	}
    33  }
    34  
    35  func TestByteRangesReader_OnPartRead(t *testing.T) {
    36  	var boundary = "7143cd51d2ee12a1"
    37  	var dashBoundary = "--" + boundary
    38  	var b = bytes.NewReader([]byte(dashBoundary + "\r\nContent-Range: bytes 0-4/36\r\nContent-Type: text/plain\r\n\r\n01234\r\n" + dashBoundary + "\r\nContent-Range: bytes 5-9/36\r\nContent-Type: text/plain\r\n\r\n56789\r\n--" + boundary + "\r\nContent-Range: bytes 10-12/36\r\nContent-Type: text/plain\r\n\r\nabc\r\n" + dashBoundary + "--\r\n"))
    39  
    40  	var reader = readers.NewByteRangesReaderCloser(io.NopCloser(b), boundary)
    41  	reader.OnPartRead(func(start int64, end int64, total int64, data []byte, header textproto.MIMEHeader) {
    42  		t.Log(start, "-", end, "/", total, string(data))
    43  	})
    44  	var p = make([]byte, 3)
    45  	for {
    46  		_, err := reader.Read(p)
    47  		if err != nil {
    48  			break
    49  		}
    50  	}
    51  }