-
Notifications
You must be signed in to change notification settings - Fork 0
/
upload.go
55 lines (49 loc) · 1.33 KB
/
upload.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
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"cloud.google.com/go/storage"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
const (
uploadURL = "https://winstrap.googlecode.com/files"
)
func Upload(filename string, content io.Reader) error {
jsonKey, err := ioutil.ReadFile(*serviceAcctJSON)
if err != nil {
return err
}
conf, err := google.JWTConfigFromJSON(jsonKey, storage.ScopeReadWrite)
if err != nil {
log.Printf("Failed to get JWT config. Get a Service Account JSON token from https://console.developers.google.com/project/999119582588/apiui/credential")
return err
}
httpClient := conf.Client(oauth2.NoContext)
const maxSlurp = 1 << 20
var buf bytes.Buffer
n, err := io.CopyN(&buf, content, maxSlurp)
if err != nil && err != io.EOF {
log.Fatalf("Error reading from stdin: %v, %v", n, err)
}
contentType := http.DetectContentType(buf.Bytes())
req, err := http.NewRequest("PUT", "https://storage.googleapis.com/winstrap/"+filename, io.MultiReader(&buf, content))
if err != nil {
return err
}
req.Header.Set("x-goog-api-version", "2")
req.Header.Set("x-goog-acl", "public-read")
req.Header.Set("Content-Type", contentType)
res, err := httpClient.Do(req)
if err != nil {
return err
}
if res.StatusCode != 200 {
return fmt.Errorf("got HTTP status %s", res.Status)
}
return nil
}