// Package catalog uploads imported products to the catalog (t5de-hub's docs/products.md, `POST /api/v1/uploads` // with a t5de-import token). The catalog checks the files, stores them and registers the revision with the hub, // which marks the job done. package catalog import ( "bytes" "context" "encoding/json" "fmt" "io" "mime/multipart" "net/http" ) // Error is the catalog's refusal: its status and `{error, message}`. type Error struct { Status int Code string Message string } func (e *Error) Error() string { if e.Message != "" { return fmt.Sprintf("the catalog refused the upload (%d %s): %s", e.Status, e.Code, e.Message) } return fmt.Sprintf("the catalog refused the upload (%d %s)", e.Status, e.Code) } // Registered is the hub's product and revision for an upload. type Registered struct { Product string `json:"product"` Revision int `json:"revision"` } // Upload posts a .chkn to the catalog's upload URL with an import token. func Upload(ctx context.Context, client *http.Client, userAgent, url, token string, chkn []byte) (*Registered, error) { var body bytes.Buffer form := multipart.NewWriter(&body) w, err := form.CreateFormFile("file", "product.chkn") if err != nil { return nil, err } if _, err := w.Write(chkn); err != nil { return nil, err } if err := form.Close(); err != nil { return nil, err } req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, &body) if err != nil { return nil, err } req.Header.Set("Authorization", "Bearer "+token) req.Header.Set("Content-Type", form.FormDataContentType()) req.Header.Set("User-Agent", userAgent) if client == nil { client = http.DefaultClient } resp, err := client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() data, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) if err != nil { return nil, err } if resp.StatusCode != http.StatusCreated { e := &Error{Status: resp.StatusCode} var r struct { Error string `json:"error"` Message string `json:"message"` } if json.Unmarshal(data, &r) == nil { e.Code, e.Message = r.Error, r.Message } return nil, e } var reg Registered if err := json.Unmarshal(data, ®); err != nil { return nil, fmt.Errorf("the catalog's answer: %w", err) } return ®, nil }