r11_urpm-repo/main.go
2025-01-31 23:52:08 +03:00

84 lines
No EOL
2.2 KiB
Go

package main
import (
"net/http"
"os"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/spf13/viper"
"github.com/kardianos/service"
)
func main() {
viper.SetConfigName("config")
viper.AddConfigPath(".")
if err := viper.ReadInConfig(); err != nil {
logger.Fatalf("Error reading config file: %v", err)
}
initLogger()
repo := NewRepository()
router := chi.NewRouter()
router.Use(middleware.Logger)
router.Use(authMiddleware)
router.Post("/{arch}", repo.UploadHandler)
svcConfig := &service.Config{
Name: "urpm-repo",
DisplayName: "URPM Repository Service",
Description: "Service for managing URPM packages",
}
s, err := service.New(&serviceProgram{repo, router}, svcConfig)
if err != nil {
logger.Fatal(err)
}
if len(os.Args) > 1 {
switch os.Args[1] {
case "install":
if err := s.Install(); err != nil {
logger.Fatal(err)
}
return
case "uninstall":
if err := s.Uninstall(); err != nil {
logger.Fatal(err)
}
return
}
}
if err := s.Run(); err != nil {
logger.Fatal(err)
}
}
type serviceProgram struct {
repo *Repository
router *chi.Mux
}
func (p *serviceProgram) Start(s service.Service) error {
logger.Info("Starting URPM Repository Service...")
go func() {
if err := http.ListenAndServe(viper.GetString("server.address"), p.router); err != nil {
logger.Error(err)
}
}()
return nil
}
func (p *serviceProgram) Stop(s service.Service) error {
logger.Info("Stopping URPM Repository Service...")
return nil
}
func authMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authToken := r.Header.Get("Authorization")
expectedToken := viper.GetString("auth.token")
if authToken != "Bearer "+expectedToken {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
logger.Error("Unauthorized access attempt")
return
}
next.ServeHTTP(w, r)
})
}