-
Notifications
You must be signed in to change notification settings - Fork 501
/
Copy pathmain.go
66 lines (58 loc) · 2.4 KB
/
main.go
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
package main
import (
"log"
"net/http"
"github.com/tus/tusd/v2/pkg/filelocker"
"github.com/tus/tusd/v2/pkg/filestore"
tusd "github.com/tus/tusd/v2/pkg/handler"
)
func main() {
// Create a new FileStore instance which is responsible for
// storing the uploaded file on disk in the specified directory.
// This path _must_ exist before tusd will store uploads in it.
// If you want to save them on a different medium, for example
// a remote FTP server, you can implement your own storage backend
// by implementing the tusd.DataStore interface.
store := filestore.New("./uploads")
// A locking mechanism helps preventing data loss or corruption from
// parallel requests to a upload resource. A good match for the disk-based
// storage is the filelocker package which uses disk-based file lock for
// coordinating access.
// More information is available at https://tus.github.io/tusd/advanced-topics/locks/.
locker := filelocker.New("./uploads")
// A storage backend for tusd may consist of multiple different parts which
// handle upload creation, locking, termination and so on. The composer is a
// place where all those separated pieces are joined together. In this example
// we only use the file store but you may plug in multiple.
composer := tusd.NewStoreComposer()
store.UseIn(composer)
locker.UseIn(composer)
// Create a new HTTP handler for the tusd server by providing a configuration.
// The StoreComposer property must be set to allow the handler to function.
handler, err := tusd.NewHandler(tusd.Config{
BasePath: "/files/",
StoreComposer: composer,
NotifyCompleteUploads: true,
})
if err != nil {
log.Fatalf("unable to create handler: %s", err)
}
// Start another goroutine for receiving events from the handler whenever
// an upload is completed. The event will contains details about the upload
// itself and the relevant HTTP request.
go func() {
for {
event := <-handler.CompleteUploads
log.Printf("Upload %s finished\n", event.Upload.ID)
}
}()
// Right now, nothing has happened since we need to start the HTTP server on
// our own. In the end, tusd will start listening on and accept request at
// http://localhost:8080/files
http.Handle("/files/", http.StripPrefix("/files/", handler))
http.Handle("/files", http.StripPrefix("/files", handler))
err = http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatalf("unable to listen: %s", err)
}
}