improve logging and error handling

This commit is contained in:
NotAShelf 2023-06-03 20:14:42 +03:00
parent 4a7e0bf614
commit 754dbf51be
No known key found for this signature in database
GPG key ID: F0D14CCB5ED5AA22
3 changed files with 68 additions and 24 deletions

6
go.mod
View file

@ -1,3 +1,9 @@
module cdn module cdn
go 1.20 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
)

14
go.sum Normal file
View file

@ -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=

72
main.go
View file

@ -4,10 +4,13 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"log"
"net/http" "net/http"
"os" "os"
"path/filepath" "path/filepath"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/sirupsen/logrus"
) )
type Config struct { type Config struct {
@ -17,41 +20,62 @@ type Config struct {
UploadsDir string `json:"uploads_dir"` UploadsDir string `json:"uploads_dir"`
} }
var ( var config Config
config Config var logger *logrus.Logger
)
func main() { func main() {
loadConfig("config.json") // Initialize logger
logger = logrus.New()
logger.Formatter = &logrus.TextFormatter{
DisableTimestamp: false,
FullTimestamp: true,
}
http.HandleFunc("/", serveCDN) // Load configuration
http.HandleFunc("/upload", handleUpload) 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) // Initialize router
log.Fatal(http.ListenAndServe(":"+config.ServicePort, nil)) 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) file, err := os.Open(filename)
if err != nil { if err != nil {
log.Fatal("Error opening config file:", err) return fmt.Errorf("error opening config file: %s", err)
} }
defer file.Close() defer file.Close()
decoder := json.NewDecoder(file) decoder := json.NewDecoder(file)
err = decoder.Decode(&config) err = decoder.Decode(&config)
if err != nil { 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) { func serveCDN(w http.ResponseWriter, r *http.Request) {
// Log the request information // 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 // Check if the request has valid authentication
if !checkAuthentication(r) { if !checkAuthentication(r) {
log.Println("Authentication failed") logger.Warn("Authentication failed")
w.Header().Set("WWW-Authenticate", `Basic realm="CDN Authentication"`) w.Header().Set("WWW-Authenticate", `Basic realm="CDN Authentication"`)
w.WriteHeader(http.StatusUnauthorized) w.WriteHeader(http.StatusUnauthorized)
fmt.Fprintf(w, "401 Unauthorized\n") fmt.Fprintf(w, "401 Unauthorized\n")
@ -65,27 +89,27 @@ func serveCDN(w http.ResponseWriter, r *http.Request) {
_, err := os.Stat(filePath) _, err := os.Stat(filePath)
if err != nil { if err != nil {
if os.IsNotExist(err) { 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) http.NotFound(w, r)
} else { } else {
log.Println("Internal Server Error") logger.Error("Internal Server Error:", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError) http.Error(w, "Internal Server Error", http.StatusInternalServerError)
} }
return return
} }
// Serve the file // Serve the file
log.Printf("Serving file: %s", r.URL.Path) logger.Infof("Serving file: %s", r.URL.Path)
http.ServeFile(w, r, filePath) http.ServeFile(w, r, filePath)
} }
func handleUpload(w http.ResponseWriter, r *http.Request) { func handleUpload(w http.ResponseWriter, r *http.Request) {
// Log the request information // 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 // Check if the request has valid authentication
if !checkAuthentication(r) { if !checkAuthentication(r) {
log.Println("Authentication failed") logger.Warn("Authentication failed")
w.Header().Set("WWW-Authenticate", `Basic realm="CDN Authentication"`) w.Header().Set("WWW-Authenticate", `Basic realm="CDN Authentication"`)
w.WriteHeader(http.StatusUnauthorized) w.WriteHeader(http.StatusUnauthorized)
fmt.Fprintf(w, "401 Unauthorized\n") fmt.Fprintf(w, "401 Unauthorized\n")
@ -95,7 +119,7 @@ func handleUpload(w http.ResponseWriter, r *http.Request) {
// Parse the uploaded file // Parse the uploaded file
file, header, err := r.FormFile("file") file, header, err := r.FormFile("file")
if err != nil { if err != nil {
log.Println("Bad Request") logger.Error("Bad Request:", err)
http.Error(w, "Bad Request", http.StatusBadRequest) http.Error(w, "Bad Request", http.StatusBadRequest)
return return
} }
@ -104,7 +128,7 @@ func handleUpload(w http.ResponseWriter, r *http.Request) {
// Create the uploads directory if it doesn't exist // Create the uploads directory if it doesn't exist
err = os.MkdirAll(config.UploadsDir, os.ModePerm) err = os.MkdirAll(config.UploadsDir, os.ModePerm)
if err != nil { if err != nil {
log.Println("Internal Server Error") logger.Error("Internal Server Error:", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError) http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return return
} }
@ -112,7 +136,7 @@ func handleUpload(w http.ResponseWriter, r *http.Request) {
// Create a new file in the uploads directory // Create a new file in the uploads directory
dst, err := os.Create(filepath.Join(config.UploadsDir, header.Filename)) dst, err := os.Create(filepath.Join(config.UploadsDir, header.Filename))
if err != nil { if err != nil {
log.Println("Internal Server Error") logger.Error("Internal Server Error:", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError) http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return return
} }
@ -121,12 +145,12 @@ func handleUpload(w http.ResponseWriter, r *http.Request) {
// Copy the uploaded file to the destination // Copy the uploaded file to the destination
_, err = io.Copy(dst, file) _, err = io.Copy(dst, file)
if err != nil { if err != nil {
log.Println("Internal Server Error") logger.Error("Internal Server Error:", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError) http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return return
} }
log.Printf("File uploaded successfully: %s", header.Filename) logger.Infof("File uploaded successfully: %s", header.Filename)
fmt.Fprintf(w, "File uploaded successfully!") fmt.Fprintf(w, "File uploaded successfully!")
} }