-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
238 lines (201 loc) · 5.65 KB
/
main.go
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
package main
import (
"crypto/rand"
"encoding/base64"
"io"
"mime"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
log "github.com/sirupsen/logrus"
)
type ErrorResponse struct {
Error string `json:"error,omitempty"`
Message string `json:"message"`
}
type DataResponse struct {
Data any `json:"data"`
}
type FileCreated struct {
Filename string `json:"filename"`
Message string `json:"message"`
Link string `json:"link"`
}
type UploadedFile struct {
Name string `json:"name"`
Type string `json:"type"`
Url string `json:"url"`
}
// Create a web server that listens on port 5890 using echo framework
func main() {
e := echo.New()
e.HidePort = true
e.HideBanner = true
//log := log.New()
e.Use(middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{
LogURI: true,
LogStatus: true,
LogValuesFunc: func(c echo.Context, values middleware.RequestLoggerValues) error {
log.WithFields(log.Fields{
"URI": values.URI,
"status": values.Status,
}).Info("request")
return nil
},
}))
e.Use(middleware.BasicAuthWithConfig(middleware.BasicAuthConfig{
Validator: func(username, password string, c echo.Context) (bool, error) {
if username == "william" && password == "3EzV8osmCog4dfp2CPj2" {
return true, nil
}
return false, nil
},
Skipper: func(c echo.Context) bool {
return c.Request().RequestURI != "/" && c.Request().Method == "GET"
},
}))
log.Infof("Starting server on port 5890")
e.GET("/", func(c echo.Context) error {
// Get a list of files in the current directory
files, err := os.ReadDir("images/")
if err != nil {
log.Error("Error reading directory")
return c.JSON(http.StatusInternalServerError, ErrorResponse{
Error: err.Error(),
Message: "Error reading directory",
})
}
// Create a slice of strings to hold the filenames
var filenames []UploadedFile
for _, file := range files {
// Append the filename to the slice
filenames = append(filenames, UploadedFile{
Name: file.Name(),
Type: mime.TypeByExtension(filepath.Ext(file.Name())),
Url: "http://localhost:5890/" + file.Name(),
})
}
// Return the filenames as a JSON response
return c.JSON(http.StatusOK, filenames)
})
e.GET("/:file_name", func(c echo.Context) error {
fileName := c.Param("file_name")
filePath := filepath.Join("images", fileName)
// Check if file exists on the server
_, err := os.OpenFile(filePath, os.O_RDONLY, 0666)
if err != nil {
return c.JSON(http.StatusNotFound, ErrorResponse{
Message: "File not found",
})
}
// Return the file to the client
return c.File(filePath)
})
// Create a route which allows images to be uploaded
e.POST("/", func(c echo.Context) error {
// Read the file from the request
file, err := c.FormFile("file")
if err != nil {
log.Errorf("Error reading file: %v", err)
return c.JSON(http.StatusBadRequest, ErrorResponse{
Error: err.Error(),
Message: "Error reading file",
})
}
fileType := filepath.Ext(file.Filename)
mimeType := mime.TypeByExtension(fileType)
if !isAllowedFile(fileType) {
log.WithFields(
log.Fields{
"file_name": file.Filename,
"file_type": fileType,
"mime_type": mimeType,
},
).Error("Tried to upload a file that is not an image/video")
return c.JSON(http.StatusBadRequest, ErrorResponse{
Message: "File is not an image",
})
}
// Get the bytes from the file
src, err := file.Open()
if err != nil {
log.Errorf("Error opening file: %v", err)
return c.JSON(http.StatusBadRequest, ErrorResponse{
Error: err.Error(),
Message: "Error opening file",
})
}
defer func(src multipart.File) {
err := src.Close()
if err != nil {
log.Errorf("Error closing file: %v", err)
}
}(src)
// Generate a new file name which is only 6 characters long
newFilename, err := GenerateRandomString(6)
if err != nil {
log.Errorf("Error generating random string: %v", err)
return c.JSON(http.StatusBadRequest, ErrorResponse{
Error: err.Error(),
Message: "Error generating random string",
})
}
// Append the file extension to the new file name
newFilename = newFilename + fileType
// Create a new file
dst, err := os.Create("images/" + newFilename)
if err != nil {
log.Errorf("Error creating file: %v", err)
return c.JSON(http.StatusBadRequest, ErrorResponse{
Error: err.Error(),
Message: "Error creating file",
})
}
defer func(dst *os.File) {
err := dst.Close()
if err != nil {
log.Errorf("Error closing file: %v", err)
}
}(dst)
// Copy the bytes from the file to the new file
if _, err = io.Copy(dst, src); err != nil {
log.Errorf("Error copying file: %v", err)
return c.JSON(http.StatusBadRequest, ErrorResponse{
Error: err.Error(),
Message: "Error copying file",
})
}
return c.JSON(http.StatusCreated, DataResponse{FileCreated{
Filename: newFilename,
Message: "File uploaded successfully",
Link: "http://localhost:5890/" + newFilename,
}})
})
e.Logger.Fatal(e.Start(":5890"))
}
// GenerateRandomString Randomly generate a string with i characters
func GenerateRandomString(n int) (string, error) {
b := make([]byte, n)
_, err := rand.Read(b)
if err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(b), nil
}
func isAllowedFile(fileType string) bool {
mimeType := mime.TypeByExtension(fileType)
if mimeType == "" {
return false
}
allowedMimeTypes := []string{"image", "video"}
for _, allowedMimeType := range allowedMimeTypes {
if strings.Contains(mimeType, allowedMimeType) {
return true
}
}
return false
}