Created
May 24, 2019 13:16
-
-
Save simcap/c318b44dbaa87fc19620765d799d623c to your computer and use it in GitHub Desktop.
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 ( | |
"crypto/sha256" | |
"fmt" | |
"io" | |
"io/ioutil" | |
"net/http" | |
) | |
type FileInfo struct { | |
sourceURL string | |
fileSHA256 string | |
fileSize int64 | |
filePath string | |
} | |
// Load a remote PDF file from a source URL | |
// and simultaneously write it locally to disk | |
// calculates its size and SHA256 checksum | |
func Load(sourceURL string) (*FileInfo, error) { | |
tmpFile, err := ioutil.TempFile("", "*.pdf") | |
if err != nil { | |
return nil, err | |
} | |
defer tmpFile.Close() | |
info := &FileInfo{ | |
sourceURL: sourceURL, | |
filePath: tmpFile.Name(), | |
} | |
resp, err := http.Get(sourceURL) | |
if err != nil { | |
return info, err | |
} | |
defer resp.Body.Close() | |
hasher := sha256.New() | |
n, err := io.Copy(io.MultiWriter(hasher, tmpFile), resp.Body) | |
if err != nil { | |
return info, err | |
} | |
info.fileSize = n | |
info.fileSHA256 = fmt.Sprintf("%x", hasher.Sum(nil)) | |
info.filePath = tmpFile.Name() | |
return info, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment