package main import ( "fmt" "net" "os" "os/signal" "strconv" "sync" "syscall" "time" "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/etag" "github.com/kanna5/qrtxt" ) func getLocalAddr() (string, error) { conn, err := net.Dial("udp", "1.0.0.1:53") if err != nil { return "", err } defer conn.Close() host, _, err := net.SplitHostPort(conn.LocalAddr().String()) return host, err } func main() { listenPort := 3000 var err error if len(os.Args) >= 2 { portStr := os.Args[1] listenPort, err = strconv.Atoi(portStr) } if err != nil { panic(fmt.Errorf("cannot parse port number: %w", err)) } if listenPort < 1 || listenPort > 65535 { panic(fmt.Errorf("invalid port number: %d", listenPort)) } localAddr, err := getLocalAddr() if err != nil { panic(fmt.Errorf("cannot get local address: %w", err)) } fullAddress := fmt.Sprintf("http://%s:%d/", localAddr, listenPort) app := fiber.New(fiber.Config{ AppName: "StaticFileServer", BodyLimit: 1, DisableStartupMessage: true, ReadTimeout: 5 * time.Second, RequestMethods: []string{"GET", "HEAD"}, ServerHeader: "StaticFileServer", }) app.Use(etag.New()) app.Static("/", "./", fiber.Static{Browse: true}) if qrText, err := qrtxt.Encode(fullAddress, qrtxt.Low); err == nil { fmt.Println(qrText) } fmt.Printf("\nListening on %s\n", fullAddress) wg := sync.WaitGroup{} wg.Add(1) go func() { defer wg.Done() err = app.Listen(":" + strconv.Itoa(listenPort)) }() sigCh := make(chan os.Signal, 1) signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM) go func() { <-sigCh _ = app.Shutdown() }() wg.Wait() if err != nil { panic(fmt.Errorf("cannot start server: %w", err)) } fmt.Println("Bye!") }