MCPcopy Index your code
hub / github.com/coder/coder / fileByID

Method fileByID

coderd/files.go:166–224  ·  view source on GitHub ↗

@Summary Get file by ID @ID get-file-by-id @Security CoderSessionToken @Tags Files @Param fileID path string true "File ID" format(uuid) @Success 200 @Router /api/v2/files/{fileID} [get]

(rw http.ResponseWriter, r *http.Request)

Source from the content-addressed store, hash-verified

164// @Success 200
165// @Router /api/v2/files/{fileID} [get]
166func (api *API) fileByID(rw http.ResponseWriter, r *http.Request) {
167 var (
168 ctx = r.Context()
169 format = r.URL.Query().Get("format")
170 )
171
172 fileID := chi.URLParam(r, "fileID")
173 if fileID == "" {
174 httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
175 Message: "File id must be provided in url.",
176 })
177 return
178 }
179
180 id, err := uuid.Parse(fileID)
181 if err != nil {
182 httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
183 Message: "File id must be a valid UUID.",
184 })
185 return
186 }
187
188 file, err := api.Database.GetFileByID(ctx, id)
189 if httpapi.Is404Error(err) {
190 httpapi.ResourceNotFound(rw)
191 return
192 }
193 if err != nil {
194 httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
195 Message: "Internal error fetching file.",
196 Detail: err.Error(),
197 })
198 return
199 }
200
201 switch format {
202 case codersdk.FormatZip:
203 if file.Mimetype != codersdk.ContentTypeTar {
204 httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
205 Message: "Only .tar files can be converted to .zip format",
206 })
207 return
208 }
209
210 rw.Header().Set("Content-Type", codersdk.ContentTypeZip)
211 rw.WriteHeader(http.StatusOK)
212 err = archive.WriteZip(rw, tar.NewReader(bytes.NewReader(file.Data)), HTTPFileMaxBytes)
213 if err != nil {
214 api.Logger.Error(ctx, "invalid .zip archive", slog.F("file_id", fileID), slog.F("mimetype", file.Mimetype), slog.Error(err))
215 }
216 case "": // no format? no conversion
217 rw.Header().Set("Content-Type", file.Mimetype)
218 _, _ = rw.Write(file.Data)
219 default:
220 httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
221 Message: "Unsupported conversion format.",
222 })
223 }

Callers

nothing calls this directly

Calls 13

WriteFunction · 0.92
Is404ErrorFunction · 0.92
ResourceNotFoundFunction · 0.92
WriteZipFunction · 0.92
ContextMethod · 0.65
GetMethod · 0.65
ParseMethod · 0.65
GetFileByIDMethod · 0.65
SetMethod · 0.65
WriteMethod · 0.65
ErrorMethod · 0.45
HeaderMethod · 0.45

Tested by

no test coverage detected