Files
coder/codersdk/files.go
T
dylanhuff-at-coder 76ae64391a refactor(codersdk): use ReadBodyAsJSON in typed endpoints (#27857)
This PR migrates 224 typed JSON response sites across 46 files to
`codersdk.ReadBodyAsJSON`, so invalid 2xx bodies return structured
errors while preserving URL credential redaction.

It intentionally excludes agent-direct HTTP, Azure IMDS, `UseNumber`,
and chat paths; stacked on coder/coder#27804, with chat and lint
follow-ups in coder/coder#27858 and coder/coder#27859. Refs
coder/coder#27044.

Reviewed and updated by Coder Agents on behalf of @dylanhuff-at-coder.
2026-08-05 13:22:23 -07:00

62 lines
1.7 KiB
Go

package codersdk
import (
"context"
"fmt"
"io"
"net/http"
"github.com/google/uuid"
)
const (
ContentTypeTar = "application/x-tar"
ContentTypeZip = "application/zip"
FormatZip = "zip"
)
// UploadResponse contains the hash to reference the uploaded file.
type UploadResponse struct {
ID uuid.UUID `json:"hash" format:"uuid"`
}
// Upload uploads an arbitrary file with the content type provided.
// This is used to upload a source-code archive.
func (c *Client) Upload(ctx context.Context, contentType string, rd io.Reader) (UploadResponse, error) {
res, err := c.Request(ctx, http.MethodPost, "/api/v2/files", rd, func(r *http.Request) {
r.Header.Set("Content-Type", contentType)
})
if err != nil {
return UploadResponse{}, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusCreated && res.StatusCode != http.StatusOK {
return UploadResponse{}, ReadBodyAsError(res)
}
var resp UploadResponse
return resp, ReadBodyAsJSON(res, &resp)
}
// Download fetches a file by uploaded hash.
func (c *Client) Download(ctx context.Context, id uuid.UUID) ([]byte, string, error) {
return c.DownloadWithFormat(ctx, id, "")
}
// Download fetches a file by uploaded hash, but it forces format conversion.
func (c *Client) DownloadWithFormat(ctx context.Context, id uuid.UUID, format string) ([]byte, string, error) {
res, err := c.Request(ctx, http.MethodGet, fmt.Sprintf("/api/v2/files/%s?format=%s", id.String(), format), nil)
if err != nil {
return nil, "", err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return nil, "", ReadBodyAsError(res)
}
data, err := io.ReadAll(res.Body)
if err != nil {
return nil, "", err
}
return data, res.Header.Get("Content-Type"), nil
}