|
| 1 | +package cli |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "io" |
| 6 | + "net/http" |
| 7 | + "strings" |
| 8 | + |
| 9 | + "golang.org/x/xerrors" |
| 10 | + |
| 11 | + "github.com/coder/coder/v2/codersdk" |
| 12 | + "github.com/coder/serpent" |
| 13 | +) |
| 14 | + |
| 15 | +// read returns a CLI command that performs an authenticated GET request to the given API path. |
| 16 | +func (r *RootCmd) read() *serpent.Command { |
| 17 | + client := new(codersdk.Client) |
| 18 | + return &serpent.Command{ |
| 19 | + Use: "read <api-path>", |
| 20 | + Short: "Read an authenticated API endpoint using your current Coder CLI token", |
| 21 | + Long: `Read an authenticated API endpoint using your current Coder CLI token. |
| 22 | +
|
| 23 | +Example: |
| 24 | + coder read workspacebuilds/my-build/logs |
| 25 | +This will perform a GET request to /api/v2/workspacebuilds/my-build/logs on the connected Coder server. |
| 26 | +`, |
| 27 | + Middleware: serpent.Chain( |
| 28 | + serpent.RequireNArgs(1), |
| 29 | + r.InitClient(client), |
| 30 | + ), |
| 31 | + Handler: func(inv *serpent.Invocation) error { |
| 32 | + apiPath := inv.Args[0] |
| 33 | + if !strings.HasPrefix(apiPath, "/") { |
| 34 | + apiPath = "/api/v2/" + apiPath |
| 35 | + } |
| 36 | + resp, err := client.Request(inv.Context(), http.MethodGet, apiPath, nil) |
| 37 | + if err != nil { |
| 38 | + return xerrors.Errorf("request failed: %w", err) |
| 39 | + } |
| 40 | + defer resp.Body.Close() |
| 41 | + if resp.StatusCode < 200 || resp.StatusCode >= 300 { |
| 42 | + body, _ := io.ReadAll(resp.Body) |
| 43 | + return xerrors.Errorf("API error: %s\n%s", resp.Status, string(body)) |
| 44 | + } |
| 45 | + |
| 46 | + contentType := resp.Header.Get("Content-Type") |
| 47 | + if strings.HasPrefix(contentType, "application/json") { |
| 48 | + // Pretty-print JSON |
| 49 | + var raw interface{} |
| 50 | + data, err := io.ReadAll(resp.Body) |
| 51 | + if err != nil { |
| 52 | + return xerrors.Errorf("failed to read response: %w", err) |
| 53 | + } |
| 54 | + err = json.Unmarshal(data, &raw) |
| 55 | + if err == nil { |
| 56 | + pretty, err := json.MarshalIndent(raw, "", " ") |
| 57 | + if err == nil { |
| 58 | + _, err = inv.Stdout.Write(pretty) |
| 59 | + if err != nil { |
| 60 | + return xerrors.Errorf("failed to write output: %w", err) |
| 61 | + } |
| 62 | + _, _ = inv.Stdout.Write([]byte("\n")) |
| 63 | + return nil |
| 64 | + } |
| 65 | + } |
| 66 | + // If JSON formatting fails, fall back to raw output |
| 67 | + _, _ = inv.Stdout.Write(data) |
| 68 | + _, _ = inv.Stdout.Write([]byte("\n")) |
| 69 | + return nil |
| 70 | + } |
| 71 | + // Non-JSON: stream as before |
| 72 | + _, err = io.Copy(inv.Stdout, resp.Body) |
| 73 | + if err != nil { |
| 74 | + return xerrors.Errorf("failed to read response: %w", err) |
| 75 | + } |
| 76 | + return nil |
| 77 | + }, |
| 78 | + } |
| 79 | +} |
0 commit comments