MCPcopy Create free account
hub / github.com/cli/cli / postAsset

Method postAsset

internal/attachments/client.go:128–174  ·  view source on GitHub ↗

postAsset does the request and reads the asset URL back. It takes the file rather than the UserAsset, because nothing about sending the bytes depends on how they render. It is separate so every way it can fail picks up the same explanation on the way out.

(ctx context.Context, a asset)

Source from the content-addressed store, hash-verified

126// how they render. It is separate so every way it can fail picks up the same
127// explanation on the way out.
128func (u *Uploader) postAsset(ctx context.Context, a asset) (string, error) {
129 url, err := safeurl.JoinPathWithHostPrefix(ghinstance.UserAssetUploadPrefix(u.host), "user-attachments", "assets")
130 if err != nil {
131 return "", err
132 }
133 url.SetQuery("name", filepath.Base(a.path))
134 url.SetQuery("content_type", a.contentType)
135 url.SetQuery("repository_id", strconv.FormatInt(u.targetRepository, 10))
136
137 open := func() (io.ReadCloser, error) { return openFile(a.path) }
138
139 f, err := open()
140 if err != nil {
141 return "", err
142 }
143 defer f.Close()
144
145 req, err := http.NewRequestWithContext(ctx, "POST", url.String(), f)
146 if err != nil {
147 return "", err
148 }
149 req.ContentLength = a.info.Size()
150 req.Header.Set("Content-Type", "application/octet-stream")
151 req.Header.Set("Accept", "application/vnd.github+json")
152 // Without GetBody a redirect re-reads an exhausted reader.
153 req.GetBody = open
154
155 // The request is hand-built and sent with DoRequest rather than Request so
156 // it can set ContentLength and GetBody, which Request cannot express.
157 resp, err := u.client.DoRequest(req)
158 if err != nil {
159 return "", err
160 }
161 defer resp.Body.Close()
162
163 var asset struct {
164 URL string `json:"url"`
165 }
166 if err := json.NewDecoder(resp.Body).Decode(&asset); err != nil {
167 return "", err
168 }
169 if asset.URL == "" {
170 return "", errors.New("the server returned no asset URL")
171 }
172
173 return asset.URL, nil
174}
175
176// newUploadError captures the status code so the message can name what the
177// endpoint refused.

Callers 1

uploadMethod · 0.95

Calls 9

JoinPathWithHostPrefixFunction · 0.92
UserAssetUploadPrefixFunction · 0.92
SetQueryMethod · 0.80
BaseMethod · 0.80
DoRequestMethod · 0.80
CloseMethod · 0.65
StringMethod · 0.65
SizeMethod · 0.65
SetMethod · 0.65

Tested by

no test coverage detected