Last active
January 12, 2020 03:49
-
-
Save ajeecai/cf2a7742bdf746efde543f34e0e4ac61 to your computer and use it in GitHub Desktop.
example on how to use go-tus for resumable file uploading with progress and speed status
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"net/http" | |
"os" | |
"sync" | |
"time" | |
tus "github.com/eventials/go-tus" | |
"github.com/eventials/go-tus/leveldbstore" | |
) | |
func main() { | |
f, err := os.Open("/path_to_bigfile") //change to your file name | |
if err != nil { | |
panic(err) | |
} | |
defer f.Close() | |
headers := make(http.Header) | |
//Create if not existing | |
store, err := leveldbstore.NewLeveldbStore("./leveldb") | |
isResume := true | |
if err != nil { | |
isResume = false | |
} | |
//looks like don't need close explicitly | |
//defer store.Close() | |
config := &tus.Config{ | |
ChunkSize: 5 * 1024 * 1024, | |
Resume: isResume, | |
OverridePatchMethod: false, | |
Store: store, | |
Header: headers, | |
} | |
client, err := tus.NewClient("http://tus_server:1080/files/", config) //change to your tus server | |
if err != nil { | |
fmt.Print("NewClient failed:", err) | |
return | |
} | |
upload, err := tus.NewUploadFromFile(f) | |
if err != nil { | |
fmt.Print("NewUploadFromFile failed:", err) | |
return | |
} | |
uploader, err := client.CreateOrResumeUpload(upload) | |
if err != nil { | |
fmt.Print("CreateOrResumeUpload failed:", err) | |
return | |
} | |
progressChan := make(chan tus.Upload) | |
defer close(progressChan) | |
uploader.NotifyUploadProgress(progressChan) | |
var wg sync.WaitGroup | |
wg.Add(1) | |
go func(wg *sync.WaitGroup, notifyChan *chan tus.Upload) { | |
fmt.Print("progress") | |
var op int64 = 0 | |
defer wg.Done() | |
for { | |
startingTime := time.Now().UTC() | |
up, ok := <-*notifyChan | |
if !ok { | |
fmt.Print("chan closed\n") | |
break | |
} | |
endingTime := time.Now().UTC() | |
var duration time.Duration = endingTime.Sub(startingTime) | |
var elapsedSec float64 = duration.Seconds() | |
speed := (float64)(config.ChunkSize) / 1024 / 1024 / elapsedSec | |
p := up.Progress() | |
if p == 100 || up.Finished() { | |
fmt.Println("...100%,Done") | |
return | |
} | |
if p != op { | |
fmt.Print("...(", fmt.Sprintf("%.3f", speed), "MB/s)", p, "%") | |
op = p | |
} | |
} | |
}(&wg, &progressChan) | |
uploader.Upload() | |
wg.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment