|
| 1 | +package http |
| 2 | + |
| 3 | +import ( |
| 4 | + "net/http" |
| 5 | + "strconv" |
| 6 | + "strings" |
| 7 | + |
| 8 | + "github.com/gorilla/mux" |
| 9 | + "github.com/hammer-code/lms-be/domain" |
| 10 | + "github.com/hammer-code/lms-be/utils" |
| 11 | +) |
| 12 | + |
| 13 | +func (h Handler) UpdateImage(w http.ResponseWriter, r *http.Request) { |
| 14 | + // Parse image ID from query or URL (misal: /images/{id}) |
| 15 | + idStr := mux.Vars(r)["id"] |
| 16 | + if idStr == "" { |
| 17 | + utils.Response(domain.HttpResponse{ |
| 18 | + Code: http.StatusBadRequest, |
| 19 | + Message: "missing image id", |
| 20 | + }, w) |
| 21 | + return |
| 22 | + } |
| 23 | + id, err := strconv.ParseUint(idStr, 10, 64) |
| 24 | + if err != nil { |
| 25 | + utils.Response(domain.HttpResponse{ |
| 26 | + Code: http.StatusBadRequest, |
| 27 | + Message: "invalid image id", |
| 28 | + }, w) |
| 29 | + return |
| 30 | + } |
| 31 | + |
| 32 | + // Parse multipart form |
| 33 | + err = r.ParseMultipartForm(10 << 20) // 10MB |
| 34 | + if err != nil { |
| 35 | + utils.Response(domain.HttpResponse{ |
| 36 | + Code: http.StatusBadRequest, |
| 37 | + Message: "failed to parse form", |
| 38 | + }, w) |
| 39 | + return |
| 40 | + } |
| 41 | + file, header, err := r.FormFile("image") |
| 42 | + if err != nil { |
| 43 | + utils.Response(domain.HttpResponse{ |
| 44 | + Code: http.StatusBadRequest, |
| 45 | + Message: "failed to get file", |
| 46 | + }, w) |
| 47 | + return |
| 48 | + } |
| 49 | + defer file.Close() |
| 50 | + |
| 51 | + category := r.FormValue("category") |
| 52 | + if category == "" { |
| 53 | + category = "public" |
| 54 | + } |
| 55 | + |
| 56 | + contentType := header.Header.Values("Content-Type")[0] |
| 57 | + contentFiles := strings.Split(contentType, "/") |
| 58 | + |
| 59 | + upload := domain.UploadImage{ |
| 60 | + File: file, |
| 61 | + Header: header, |
| 62 | + Category: category, |
| 63 | + ContentType: contentType, |
| 64 | + Format: contentFiles[1], |
| 65 | + Type: contentFiles[0], |
| 66 | + } |
| 67 | + |
| 68 | + ctx := r.Context() |
| 69 | + err = h.usecase.UpdateImage(ctx, upload, uint(id)) |
| 70 | + if err != nil { |
| 71 | + utils.Response(domain.HttpResponse{ |
| 72 | + Code: http.StatusInternalServerError, |
| 73 | + Message: err.Error(), |
| 74 | + }, w) |
| 75 | + return |
| 76 | + } |
| 77 | + |
| 78 | + utils.Response(domain.HttpResponse{ |
| 79 | + Code: 200, |
| 80 | + Message: "Image updated successfully", |
| 81 | + }, w) |
| 82 | +} |
| 83 | + |
0 commit comments