go-cdn/main.go

207 lines
5.5 KiB
Go
Raw Normal View History

2023-06-03 15:55:38 +00:00
package main
import (
2023-06-03 16:53:48 +00:00
"encoding/json"
2023-06-03 19:23:41 +00:00
"flag"
2023-06-03 15:55:38 +00:00
"fmt"
2023-06-03 16:20:16 +00:00
"io"
2023-06-03 19:23:41 +00:00
"log"
2023-06-03 15:55:38 +00:00
"net/http"
"os"
"path/filepath"
2023-06-03 19:23:41 +00:00
"time"
2023-06-03 17:14:42 +00:00
"github.com/sirupsen/logrus"
2023-06-03 15:55:38 +00:00
)
2023-06-03 19:23:41 +00:00
// Config represents the configuration structure
2023-06-03 16:53:48 +00:00
type Config struct {
2023-06-03 19:23:41 +00:00
Port string `json:"port"`
MaxUploadSize int64 `json:"max_upload_size"`
Heartbeat Duration `json:"heartbeat"`
RequireAuth bool `json:"require_auth"`
AuthUsername string `json:"auth_username"`
AuthPassword string `json:"auth_password"`
UploadDirectory string `json:"upload_directory"`
2023-06-03 16:53:48 +00:00
}
2023-06-03 19:23:41 +00:00
// Duration is a custom type for decoding time.Duration from JSON
type Duration time.Duration
2023-06-03 15:55:38 +00:00
2023-06-03 19:23:41 +00:00
// UnmarshalJSON unmarshals a JSON string into a Duration
func (d *Duration) UnmarshalJSON(data []byte) error {
var durationStr string
if err := json.Unmarshal(data, &durationStr); err != nil {
return fmt.Errorf("error decoding Duration: %w", err)
2023-06-03 17:14:42 +00:00
}
2023-06-03 19:23:41 +00:00
parsedDuration, err := time.ParseDuration(durationStr)
2023-06-03 17:14:42 +00:00
if err != nil {
2023-06-03 19:23:41 +00:00
return fmt.Errorf("error parsing Duration: %w", err)
2023-06-03 17:14:42 +00:00
}
2023-06-03 19:23:41 +00:00
*d = Duration(parsedDuration)
return nil
}
2023-06-03 19:23:41 +00:00
// CDNHandler handles HTTP requests to the CDN server
type CDNHandler struct {
Config Config
Logger *logrus.Logger
}
2023-06-03 19:23:41 +00:00
// ServeHTTP serves HTTP requests
func (c *CDNHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
c.handleGet(w, r)
case http.MethodPost:
c.handlePost(w, r)
default:
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
2023-06-03 17:14:42 +00:00
}
2023-06-03 16:53:48 +00:00
}
2023-06-03 19:23:41 +00:00
// handleGet handles GET requests
func (c *CDNHandler) handleGet(w http.ResponseWriter, r *http.Request) {
c.Logger.Infof("Received GET request for URL: %s", r.URL.Path)
2023-06-03 19:23:41 +00:00
// Serve file for download
filePath := filepath.Join(c.Config.UploadDirectory, r.URL.Path)
file, err := os.Open(filePath)
2023-06-03 16:53:48 +00:00
if err != nil {
2023-06-03 19:23:41 +00:00
c.Logger.Errorf("Error opening file: %v", err)
http.Error(w, "File Not Found", http.StatusNotFound)
return
2023-06-03 16:53:48 +00:00
}
defer file.Close()
2023-06-03 19:23:41 +00:00
// Set the appropriate Content-Type header based on file extension
contentType := "application/octet-stream"
switch filepath.Ext(filePath) {
case ".jpg", ".jpeg":
contentType = "image/jpeg"
case ".png":
contentType = "image/png"
case ".pdf":
contentType = "application/pdf"
2023-06-03 16:53:48 +00:00
}
2023-06-03 17:14:42 +00:00
2023-06-03 19:23:41 +00:00
w.Header().Set("Content-Type", contentType)
if _, err := io.Copy(w, file); err != nil {
c.Logger.Errorf("Error copying file: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
2023-06-03 19:23:41 +00:00
c.Logger.Infof("File downloaded successfully: %s", r.URL.Path)
2023-06-03 15:55:38 +00:00
}
2023-06-03 19:23:41 +00:00
// handlePost handles POST requests
func (c *CDNHandler) handlePost(w http.ResponseWriter, r *http.Request) {
c.Logger.Info("Received POST request")
2023-06-03 15:55:38 +00:00
2023-06-03 19:23:41 +00:00
// Validate request size
r.Body = http.MaxBytesReader(w, r.Body, c.Config.MaxUploadSize)
if err := r.ParseMultipartForm(c.Config.MaxUploadSize); err != nil {
c.Logger.Errorf("Error parsing multipart form: %v", err)
http.Error(w, "Payload Too Large", http.StatusRequestEntityTooLarge)
2023-06-03 15:55:38 +00:00
return
}
2023-06-03 19:23:41 +00:00
// Get the uploaded file
file, handler, err := r.FormFile("file")
2023-06-03 15:55:38 +00:00
if err != nil {
2023-06-03 19:23:41 +00:00
c.Logger.Errorf("Error retrieving file: %v", err)
http.Error(w, "Error retrieving file", http.StatusInternalServerError)
2023-06-03 15:55:38 +00:00
return
}
2023-06-03 19:23:41 +00:00
defer file.Close()
2023-06-03 15:55:38 +00:00
2023-06-03 19:23:41 +00:00
// Create the upload directory if it doesn't exist
uploadDir := c.Config.UploadDirectory
if uploadDir == "" {
uploadDir = "uploads"
2023-06-03 15:55:38 +00:00
}
2023-06-03 19:23:41 +00:00
if err := os.MkdirAll(uploadDir, os.ModePerm); err != nil {
c.Logger.Errorf("Error creating upload directory: %v", err)
http.Error(w, "Error creating upload directory", http.StatusInternalServerError)
2023-06-03 15:55:38 +00:00
return
}
2023-06-03 17:42:30 +00:00
2023-06-03 19:23:41 +00:00
// Create the file in the upload directory
filePath := filepath.Join(uploadDir, handler.Filename)
newFile, err := os.Create(filePath)
2023-06-03 17:42:30 +00:00
if err != nil {
2023-06-03 19:23:41 +00:00
c.Logger.Errorf("Error creating file: %v", err)
http.Error(w, "Error creating file", http.StatusInternalServerError)
2023-06-03 17:42:30 +00:00
return
}
2023-06-03 19:23:41 +00:00
defer newFile.Close()
2023-06-03 15:55:38 +00:00
2023-06-03 19:23:41 +00:00
// Copy the uploaded file to the new file
if _, err := io.Copy(newFile, file); err != nil {
c.Logger.Errorf("Error copying file: %v", err)
http.Error(w, "Error copying file", http.StatusInternalServerError)
2023-06-03 17:42:30 +00:00
return
}
2023-06-03 19:23:41 +00:00
c.Logger.Infof("File uploaded successfully: %s", handler.Filename)
fmt.Fprint(w, "File uploaded successfully")
}
2023-06-03 15:55:38 +00:00
2023-06-03 19:23:41 +00:00
func main() {
// Parse command line flags
configPath := flag.String("config", "config.json", "Path to the configuration file")
flag.Parse()
// Initialize logrus logger
logger := logrus.New()
logger.SetFormatter(&logrus.TextFormatter{
FullTimestamp: true,
TimestampFormat: "2006-01-02 15:04:05",
})
// Read the configuration file
configFile, err := os.Open(*configPath)
2023-06-03 15:55:38 +00:00
if err != nil {
2023-06-03 19:23:41 +00:00
logger.Fatalf("Error opening configuration file: %v", err)
2023-06-03 15:55:38 +00:00
}
2023-06-03 19:23:41 +00:00
defer configFile.Close()
2023-06-03 15:55:38 +00:00
2023-06-03 19:23:41 +00:00
// Decode the configuration file
var config Config
err = json.NewDecoder(configFile).Decode(&config)
2023-06-03 15:55:38 +00:00
if err != nil {
2023-06-03 19:23:41 +00:00
logger.Fatalf("Error decoding configuration file: %v", err)
2023-06-03 15:55:38 +00:00
}
2023-06-03 19:23:41 +00:00
// Start a goroutine to restart the server periodically
if config.Heartbeat > 0 {
go func() {
for range time.Tick(time.Duration(config.Heartbeat)) {
logger.Info("Server heartbeat")
os.Exit(0)
}
}()
}
2023-06-03 19:23:41 +00:00
// Create a new CDNHandler with the configuration
cdnHandler := &CDNHandler{
Config: config,
Logger: logger,
}
2023-06-03 19:23:41 +00:00
// Create a new HTTP server
server := &http.Server{
Addr: ":" + config.Port,
Handler: cdnHandler,
ErrorLog: log.New(logger.Writer(), "", 0),
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}
2023-06-03 19:23:41 +00:00
logger.Infof("Starting CDN server on port %s", config.Port)
log.Fatal(server.ListenAndServe())
}