From 8d8a5a33babf1c3b58cb284146be0dcff608b877 Mon Sep 17 00:00:00 2001 From: Kyle Conroy Date: Sun, 27 Feb 2022 22:18:13 -0800 Subject: [PATCH] Add better error messages Don't make a request if the API token is missing --- internal/bundler/upload.go | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/internal/bundler/upload.go b/internal/bundler/upload.go index d798a1d96a..899eb0e4d7 100644 --- a/internal/bundler/upload.go +++ b/internal/bundler/upload.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "fmt" + "io" "mime/multipart" "net/http" "os" @@ -12,6 +13,7 @@ import ( ) type Uploader struct { + token string configPath string config *config.Config dir string @@ -19,6 +21,7 @@ type Uploader struct { func NewUploader(configPath, dir string, conf *config.Config) *Uploader { return &Uploader{ + token: os.Getenv("SQLC_AUTH_TOKEN"), configPath: configPath, config: conf, dir: dir, @@ -27,7 +30,10 @@ func NewUploader(configPath, dir string, conf *config.Config) *Uploader { func (up *Uploader) Validate() error { if up.config.Project.ID == "" { - return fmt.Errorf("project ID is not set") + return fmt.Errorf("project.id is not set") + } + if up.token == "" { + return fmt.Errorf("SQLC_AUTH_TOKEN environment variable is not set") } return nil } @@ -40,24 +46,22 @@ func (up *Uploader) Upload(ctx context.Context, result map[string]string) error w := multipart.NewWriter(body) defer w.Close() - if err := writeInputs(w, up.configPath, up.config); err != nil { return err } if err := writeOutputs(w, up.dir, result); err != nil { return err } - w.Close() - req, err := http.NewRequest("POST", "http://localhost:8090/upload", body) + req, err := http.NewRequest("POST", "https://api.sqlc.dev/upload", body) if err != nil { return err } // Set sqlc-version header req.Header.Set("Content-Type", w.FormDataContentType()) - req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", os.Getenv("SQLC_AUTH_TOKEN"))) + req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", up.token)) req = req.WithContext(ctx) client := &http.Client{} @@ -66,7 +70,12 @@ func (up *Uploader) Upload(ctx context.Context, result map[string]string) error return err } if resp.StatusCode >= 400 { - return fmt.Errorf("upload endpiont returned non-200 status code: %d", resp.StatusCode) + body, err := io.ReadAll(resp.Body) + defer resp.Body.Close() + if err != nil { + return fmt.Errorf("upload error: endpoint returned non-200 status code: %d", resp.StatusCode) + } + return fmt.Errorf("upload error: %d: %s", resp.StatusCode, string(body)) } return nil }