-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathattachment.go
More file actions
92 lines (73 loc) · 2.31 KB
/
attachment.go
File metadata and controls
92 lines (73 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package app
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
gitlab "gitlab.com/gitlab-org/api/client-go"
)
type FileReader interface {
ReadFile(path string) (io.Reader, error)
}
type AttachmentRequest struct {
FilePath string `json:"file_path" validate:"required"`
FileName string `json:"file_name" validate:"required"`
}
type AttachmentResponse struct {
SuccessResponse
Markdown string `json:"markdown"`
Alt string `json:"alt"`
Url string `json:"url"`
}
type attachmentReader struct{}
func (ar attachmentReader) ReadFile(path string) (io.Reader, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
data, err := io.ReadAll(file)
if err != nil {
return nil, err
}
defer file.Close()
reader := bytes.NewReader(data)
return reader, nil
}
type FileUploader interface {
UploadProjectMarkdown(pid any, content io.Reader, filename string, options ...gitlab.RequestOptionFunc) (*gitlab.ProjectMarkdownUploadedFile, *gitlab.Response, error)
}
type attachmentService struct {
data
fileReader FileReader
client FileUploader
}
/* attachmentHandler uploads an attachment (file, image, etc) to Gitlab and returns metadata about the upload. */
func (a attachmentService) ServeHTTP(w http.ResponseWriter, r *http.Request) {
payload := r.Context().Value(payload("payload")).(*AttachmentRequest)
file, err := a.fileReader.ReadFile(payload.FilePath)
if err != nil || file == nil {
handleError(w, err, fmt.Sprintf("Could not read %s file", payload.FileName), http.StatusInternalServerError)
return
}
projectFile, res, err := a.client.UploadProjectMarkdown(a.projectInfo.ProjectId, file, payload.FileName)
if err != nil {
handleError(w, err, fmt.Sprintf("Could not upload %s to Gitlab", payload.FileName), http.StatusInternalServerError)
return
}
if res.StatusCode >= 300 {
handleError(w, GenericError{r.URL.Path}, fmt.Sprintf("Could not upload %s to Gitlab", payload.FileName), res.StatusCode)
return
}
response := AttachmentResponse{
SuccessResponse: SuccessResponse{Message: "File uploaded successfully"},
Markdown: projectFile.Markdown,
Alt: projectFile.Alt,
Url: projectFile.URL,
}
err = json.NewEncoder(w).Encode(response)
if err != nil {
handleError(w, err, "Could not encode response", http.StatusInternalServerError)
}
}