Documentation ¶
Overview ¶
Package ctxdownload is a Golang package which provides helper functions for performing context-aware download task.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Download ¶
func Download(ctx context.Context, url, outDir, fileName string, buf []byte, requestTimeoutSeconds int) (downloadedFileName string, err error)
Download downloads the file from HTTP server.
Params: ctx: Google's Context type which carries deadlines, cacelation signals, and other request-scoped values across API boundaries and between processes. See https://godoc.org/golang.org/x/net/context for more. url: Download URL outDir: Directory to store the downloaded file. fileName: Downloaded file name(base name). If the given file name is empty(""), it'll detect the file name in response header. buf: Buffer(length should >= 0). requestTimeoutSeconds: HTTP request timeout. It's NOT download timeout. Default value(defRequestTimeoutSeconds) is 10 seconds. Return: downloadedFileName: Absolute downloaded file path.
Example ¶
Run "go test -c && ./ctxdownload.test"
package main import ( "fmt" "os" "time" "github.com/northbright/ctx/ctxdownload" "golang.org/x/net/context" ) func main() { // Download a zip file to test ctxdownload.Download(). url := "https://github.com/northbright/plants/archive/master.zip" outDir := "./download" fileName := "" // If file name is empty, it will try to detect file name in response Header in Download(). // Set total timeout. You'll get "deadline exceeded" error as expected. // To make download successful, set it to 300 or longer. totalTimeoutSeconds := 20 totalTimeout := time.Duration(time.Duration(totalTimeoutSeconds) * time.Second) // Make a context to carry a deadline(timeout). // See http://blog.golang.org/context to for more information. ctx, cancel := context.WithTimeout(context.Background(), totalTimeout) defer cancel() // HTTP request timeout(NOT download timeout). requestTimeoutSeconds := 10 // Make buffer. buf := make([]byte, 2*1024*1024) // Start download. // It will cancel download if cancel() is called in other goroutines. // It will stop download if deadline is exceeded(timeout). downloadedFileName, err := ctxdownload.Download(ctx, url, outDir, fileName, buf, requestTimeoutSeconds) if err != nil { fmt.Fprintf(os.Stderr, "ctxdownload.Download() err: %v\n", err) } else { fmt.Fprintf(os.Stderr, "ctxdownload.Download() succeeded.\nDownloaded File: %v\n", downloadedFileName) } }
Output:
Types ¶
This section is empty.
Click to show internal directories.
Click to hide internal directories.