Last active
October 28, 2021 06:24
-
-
Save imjasonh/bd6a7fa7a94648324f3f to your computer and use it in GitHub Desktop.
Script to upload a file to Drive, request it be converted to spreadsheet, then export it as CSV
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 ( | |
"encoding/json" | |
"flag" | |
"io" | |
"log" | |
"net/http" | |
"os" | |
"strings" | |
) | |
var ( | |
file = flag.String("file", "", "file to convert") | |
token = flag.String("token", "", "access token authorized to Drive API") | |
) | |
// RoundTripper that adds a token before making the request. | |
type tokenRT struct{} | |
func (t tokenRT) RoundTrip(r *http.Request) (*http.Response, error) { | |
r.Header.Set("Authorization", "Bearer "+*token) | |
c := http.Client{} | |
return c.Do(r) | |
} | |
func main() { | |
flag.Parse() | |
f, err := os.Open(*file) | |
if err != nil { | |
log.Fatalf("%v", err) | |
} | |
defer f.Close() | |
c := http.Client{ | |
Transport: tokenRT{}, | |
} | |
// Upload file and request conversion | |
iresp, err := c.Post("https://www.googleapis.com/upload/drive/v2/files?uploadType=media&convert=true", "application/vnd.ms-excel", f) | |
if err != nil { | |
log.Fatalf("%v", err) | |
} | |
defer iresp.Body.Close() | |
if iresp.StatusCode != http.StatusOK { | |
io.Copy(os.Stderr, iresp.Body) | |
log.Fatalf("Error %d", iresp.StatusCode) | |
} | |
// Get the link to export to CSV | |
var insertResp struct { | |
ID string | |
ExportLinks map[string]string | |
} | |
if err := json.NewDecoder(iresp.Body).Decode(&insertResp); err != nil { | |
log.Fatalf("%v", err) | |
} | |
link := insertResp.ExportLinks["application/pdf"] | |
if link == "" { | |
log.Fatalf("couldn't get export link") | |
} | |
link = strings.Replace(link, "=pdf", "=csv", 1) + "&access_token=" + *token | |
// Fetch export link | |
eresp, err := http.Get(link) | |
if err != nil { | |
log.Fatalf("%v", err) | |
} | |
defer eresp.Body.Close() | |
if eresp.StatusCode != http.StatusOK { | |
io.Copy(os.Stderr, eresp.Body) | |
log.Fatalf("Error %d", eresp.StatusCode) | |
} | |
io.Copy(os.Stdout, eresp.Body) | |
// Trash temporary file uploaded for conversion | |
if _, err := c.Post("https://www.googleapis.com/drive/v2/files/"+insertResp.ID+"/trash", "application/json", nil); err != nil { | |
log.Printf("failed to trash: %v", err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment