-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
95 lines (79 loc) · 2.09 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
package main
import (
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"github.com/joho/godotenv"
"go.uber.org/zap"
)
var (
ApiKey string
logger *zap.Logger
)
func initLogger() {
var err error
logger, err = zap.NewProduction()
if err != nil {
panic(err)
}
logger.Info("Logger initialized")
}
func loadAPIKey() error {
godotenv.Load(".env")
ApiKey = os.Getenv("API_KEY")
if ApiKey == "" {
logger.Error("API key is not set")
return fmt.Errorf("API key is not set")
}
logger.Info("API key loaded")
return nil
}
func uploadFile(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
logger.Error("Invalid request method", zap.String("method", r.Method))
http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
return
}
if r.Header.Get("X-API-Key") != ApiKey {
logger.Warn("Invalid API Key provided", zap.String("provided_api_key", r.Header.Get("X-API-Key")))
http.Error(w, "Invalid API Key", http.StatusForbidden)
return
}
file, handler, err := r.FormFile("file")
if err != nil {
logger.Error("Error retrieving file from form", zap.Error(err))
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
defer file.Close()
filePath := filepath.Join("uploads", handler.Filename)
out, err := os.Create(filePath)
if err != nil {
logger.Error("Error creating file", zap.String("file_path", filePath), zap.Error(err))
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer out.Close()
_, err = io.Copy(out, file)
if err != nil {
logger.Error("Error copying file", zap.Error(err))
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
logger.Info("Successfully uploaded file", zap.String("file_path", filePath))
fmt.Fprintf(w, "Successfully uploaded file\n")
}
func main() {
initLogger()
err := loadAPIKey()
if err != nil {
logger.Fatal("Failed to load API key", zap.Error(err))
return
}
http.HandleFunc("/upload", uploadFile)
http.Handle("/files/", http.StripPrefix("/files/", http.FileServer(http.Dir("uploads"))))
logger.Info("Server starting on port 8080")
http.ListenAndServe(":8080", nil)
}