golang 实现文件断点续传 demo

golang 实现文件断点续传 demo

实现http断点续传其中一种办法是使用范围请求

涉及头部:

request

  • Range 表示获取数据范围。例如:Range: bytes=0-1023表示获取下标为01023的字节,一共1024个。

response

  • Content-Range 表示返回数据的范围。例如Content-Range: bytes 0-1023/146515表示当前http报文的body数据是0-1023,文件一共有146515个字节。

  • Accept-Ranges 表示接受range的单位,目前只定义了bytes。服务器返回这个头部则表明接收范围请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package main

import (
"flag"
"fmt"
"github.com/gorilla/mux"
"io"
"log"
"net/http"
"os"
"strconv"
"strings"
)

func main() {
path := ""
port := ""
flag.StringVar(&path,"dir", "", "the dir to server")
flag.StringVar(&port,"port", "", "server port")
flag.Parse()
port = ":" + port
if strings.LastIndexByte(path,'/') != len(path) - 1{
path = path + "/"
}
r := mux.NewRouter()
r.HandleFunc("/{file}", func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
f := vars["file"]
var start, end int64
fmt.Sscanf(r.Header.Get("Range"), "bytes=%d-%d", &start, &end)
file, err := os.Open(path + f)
if err != nil {
log.Println(err.Error())
http.NotFound(w, r)
return
}
info, err := file.Stat()
if err != nil {
log.Println(err.Error())
http.NotFound(w, r)
return
}
if start < 0 ||start >= info.Size() ||end < 0 || end >= info.Size(){
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(fmt.Sprintf("out of index, length:%d",info.Size())))
return
}
if end == 0 {
end = info.Size() - 1
}
w.Header().Add("Accept-ranges", "bytes")
w.Header().Add("Content-Length", strconv.FormatInt(end-start+1, 10))
w.Header().Add("Content-Range", "bytes "+strconv.FormatInt(start, 10)+"-"+strconv.FormatInt(end, 10)+"/"+strconv.FormatInt(info.Size()-start, 10))
w.Header().Add("Content-Disposition", "attachment; filename="+info.Name())
_, err = file.Seek(start, 0)
if err != nil {
log.Println(err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
_, err = io.CopyN(w, file, end-start+1)
if err != nil {
log.Println(err.Error())
return
}
})
http.ListenAndServe(port, r)
}

待改进

如果在断点后再继续传输并且对象发生变化,那么会出现错误,所以要加上 Last-Modified 或者 ETag 来判断对象是否已经改变。