github.com/iikira/iikira-go-utils@v0.0.0-20230610031953-f2cb11cde33a/requester/downloader/download_firstinfo.go (about)

     1  package downloader
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  	"reflect"
     7  )
     8  
     9  type (
    10  	DownloadFirstInfo struct {
    11  		ContentLength int64
    12  		ContentMD5    string
    13  		ContentCRC32  string
    14  		AcceptRanges  string
    15  		Referer       string
    16  	}
    17  )
    18  
    19  func NewDownloadFirstInfoByResp(contentLength int64, resp *http.Response) (dfi *DownloadFirstInfo) {
    20  	dfi = &DownloadFirstInfo{}
    21  	if resp == nil {
    22  		dfi.ContentLength = contentLength
    23  		return
    24  	}
    25  	if contentLength != resp.ContentLength {
    26  		dfi.ContentLength = contentLength
    27  	}
    28  	dfi.AcceptRanges = resp.Header.Get("Accept-Ranges")
    29  	dfi.Referer = resp.Header.Get("Referer")
    30  	return
    31  }
    32  
    33  func (dfi *DownloadFirstInfo) Compare(n *DownloadFirstInfo) bool {
    34  	if n == nil {
    35  		return false
    36  	}
    37  	if dfi.ContentLength != n.ContentLength {
    38  		return false
    39  	}
    40  	if dfi.AcceptRanges != n.AcceptRanges {
    41  		return false
    42  	}
    43  	if dfi.Referer != n.Referer {
    44  		return false
    45  	}
    46  	return true
    47  }
    48  
    49  // ToMap 转换为map
    50  func (dfi *DownloadFirstInfo) ToMap() map[string]string {
    51  	m := map[string]string{
    52  		"Content-MD5":     dfi.ContentMD5,
    53  		"x-bs-meta-crc32": dfi.ContentCRC32,
    54  		"Accept-Ranges":   dfi.AcceptRanges,
    55  		"Referer":         dfi.Referer,
    56  	}
    57  	return m
    58  }
    59  
    60  // ToMapByReflect 用reflect转换为map
    61  func (dfi *DownloadFirstInfo) ToMapByReflect() map[string]string {
    62  	te := reflect.TypeOf(dfi).Elem()
    63  	ve := reflect.ValueOf(dfi).Elem()
    64  	n := te.NumField()
    65  	m := map[string]string{}
    66  	for i := 0; i < n; i++ {
    67  		f := te.Field(i)
    68  		m[f.Name] = fmt.Sprint(ve.Field(i).Interface())
    69  	}
    70  	return m
    71  }