From 754dbf51be122a8e4e932ae4a3e1457a7295e6e1 Mon Sep 17 00:00:00 2001 From: NotAShelf Date: Sat, 3 Jun 2023 20:14:42 +0300 Subject: [PATCH] improve logging and error handling --- go.mod | 6 +++++ go.sum | 14 +++++++++++ main.go | 72 ++++++++++++++++++++++++++++++++++++++------------------- 3 files changed, 68 insertions(+), 24 deletions(-) create mode 100644 go.sum diff --git a/go.mod b/go.mod index 8aecc5e..c558bb4 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,9 @@ module cdn go 1.20 + +require ( + github.com/go-chi/chi v1.5.4 // indirect + github.com/sirupsen/logrus v1.9.2 // indirect + golang.org/x/sys v0.8.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..6086439 --- /dev/null +++ b/go.sum @@ -0,0 +1,14 @@ +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/go-chi/chi v1.5.4 h1:QHdzF2szwjqVV4wmByUnTcsbIg7UGaQ0tPF2t5GcAIs= +github.com/go-chi/chi v1.5.4/go.mod h1:uaf8YgoFazUOkPBG7fxPftUylNumIev9awIWOENIuEg= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/sirupsen/logrus v1.9.2 h1:oxx1eChJGI6Uks2ZC4W1zpLlVgqB8ner4EuQwV4Ik1Y= +github.com/sirupsen/logrus v1.9.2/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.8.0 h1:EBmGv8NaZBZTWvrbjNoL6HVt+IVy3QDQpJs7VRIw3tU= +golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/main.go b/main.go index 45b3a54..c190f17 100644 --- a/main.go +++ b/main.go @@ -4,10 +4,13 @@ import ( "encoding/json" "fmt" "io" - "log" "net/http" "os" "path/filepath" + + "github.com/go-chi/chi" + "github.com/go-chi/chi/middleware" + "github.com/sirupsen/logrus" ) type Config struct { @@ -17,41 +20,62 @@ type Config struct { UploadsDir string `json:"uploads_dir"` } -var ( - config Config -) +var config Config +var logger *logrus.Logger func main() { - loadConfig("config.json") + // Initialize logger + logger = logrus.New() + logger.Formatter = &logrus.TextFormatter{ + DisableTimestamp: false, + FullTimestamp: true, + } - http.HandleFunc("/", serveCDN) - http.HandleFunc("/upload", handleUpload) + // Load configuration + err := loadConfig("config.json") + if err != nil { + logger.Fatalf("Error loading config file: %s", err) + } - log.Printf("Starting CDN server on port %s...\n", config.ServicePort) - log.Fatal(http.ListenAndServe(":"+config.ServicePort, nil)) + // Initialize router + router := chi.NewRouter() + router.Use(middleware.Logger) + + router.HandleFunc("/", serveCDN) + router.HandleFunc("/upload", handleUpload) + + // Start server + address := fmt.Sprintf(":%s", config.ServicePort) + logger.Infof("Starting CDN server on port %s...", config.ServicePort) + err = http.ListenAndServe(address, router) + if err != nil { + logger.Fatalf("Server error: %s", err) + } } -func loadConfig(filename string) { +func loadConfig(filename string) error { file, err := os.Open(filename) if err != nil { - log.Fatal("Error opening config file:", err) + return fmt.Errorf("error opening config file: %s", err) } defer file.Close() decoder := json.NewDecoder(file) err = decoder.Decode(&config) if err != nil { - log.Fatal("Error decoding config file:", err) + return fmt.Errorf("error decoding config file: %s", err) } + + return nil } func serveCDN(w http.ResponseWriter, r *http.Request) { // Log the request information - log.Printf("Received request: %s %s", r.Method, r.URL.Path) + logger.Infof("Received request: %s %s", r.Method, r.URL.Path) // Check if the request has valid authentication if !checkAuthentication(r) { - log.Println("Authentication failed") + logger.Warn("Authentication failed") w.Header().Set("WWW-Authenticate", `Basic realm="CDN Authentication"`) w.WriteHeader(http.StatusUnauthorized) fmt.Fprintf(w, "401 Unauthorized\n") @@ -65,27 +89,27 @@ func serveCDN(w http.ResponseWriter, r *http.Request) { _, err := os.Stat(filePath) if err != nil { if os.IsNotExist(err) { - log.Printf("File not found: %s", r.URL.Path) + logger.Infof("File not found: %s", r.URL.Path) http.NotFound(w, r) } else { - log.Println("Internal Server Error") + logger.Error("Internal Server Error:", err) http.Error(w, "Internal Server Error", http.StatusInternalServerError) } return } // Serve the file - log.Printf("Serving file: %s", r.URL.Path) + logger.Infof("Serving file: %s", r.URL.Path) http.ServeFile(w, r, filePath) } func handleUpload(w http.ResponseWriter, r *http.Request) { // Log the request information - log.Printf("Received upload request: %s %s", r.Method, r.URL.Path) + logger.Infof("Received upload request: %s %s", r.Method, r.URL.Path) // Check if the request has valid authentication if !checkAuthentication(r) { - log.Println("Authentication failed") + logger.Warn("Authentication failed") w.Header().Set("WWW-Authenticate", `Basic realm="CDN Authentication"`) w.WriteHeader(http.StatusUnauthorized) fmt.Fprintf(w, "401 Unauthorized\n") @@ -95,7 +119,7 @@ func handleUpload(w http.ResponseWriter, r *http.Request) { // Parse the uploaded file file, header, err := r.FormFile("file") if err != nil { - log.Println("Bad Request") + logger.Error("Bad Request:", err) http.Error(w, "Bad Request", http.StatusBadRequest) return } @@ -104,7 +128,7 @@ func handleUpload(w http.ResponseWriter, r *http.Request) { // Create the uploads directory if it doesn't exist err = os.MkdirAll(config.UploadsDir, os.ModePerm) if err != nil { - log.Println("Internal Server Error") + logger.Error("Internal Server Error:", err) http.Error(w, "Internal Server Error", http.StatusInternalServerError) return } @@ -112,7 +136,7 @@ func handleUpload(w http.ResponseWriter, r *http.Request) { // Create a new file in the uploads directory dst, err := os.Create(filepath.Join(config.UploadsDir, header.Filename)) if err != nil { - log.Println("Internal Server Error") + logger.Error("Internal Server Error:", err) http.Error(w, "Internal Server Error", http.StatusInternalServerError) return } @@ -121,12 +145,12 @@ func handleUpload(w http.ResponseWriter, r *http.Request) { // Copy the uploaded file to the destination _, err = io.Copy(dst, file) if err != nil { - log.Println("Internal Server Error") + logger.Error("Internal Server Error:", err) http.Error(w, "Internal Server Error", http.StatusInternalServerError) return } - log.Printf("File uploaded successfully: %s", header.Filename) + logger.Infof("File uploaded successfully: %s", header.Filename) fmt.Fprintf(w, "File uploaded successfully!") }