web services - Why is my video file server written in GO not broadcasting over the WIFI network? - Stack Overflow

I wrote the following video file server in GO. I quite enjoyed doing it, but it is not working like I w

I wrote the following video file server in GO. I quite enjoyed doing it, but it is not working like I wanted it to. The file server works fine on the host machine, but for some reason, the other mobile devices on the same WIFI network are not picking up the server.

I have a main.go that is the starting point of the application and then a file_server.go file that hosts the server logic and then also a mdns.go file that hosts the broadcasting over mdns logic. I also have a network_interface.go file that gets the host machine's IP address.

When I enter the http://192.168.1.100:8080/videos/ into the web browser. It opens fine on the host PC, but not on other devices on the same WIFI network. The server is just not broadcasting correctly to other devices on the same WIFI network. I'm on a Windows machine.

Here is my code any help will be appreciated.

main.go

package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
    "path/filepath"
    "strings"
    "time"

    "video-server/auth"
    "video-server/file_server"
    "video-server/mdns"
    "video-server/network_interface"
    "video-server/ui"
)

func main() {
    // Ask for a Username
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Enter username: ")
    username, _ := reader.ReadString('\n')
    username = strings.TrimSpace(username)

    // Ask for a Password
    fmt.Print("Enter password: ")
    password, _ := reader.ReadString('\n')
    password = strings.TrimSpace(password)

    // Set authentication credentials
    if err := auth.SetCredentials(username, password); err != nil {
        log.Fatalf("Failed to set credentials: %v", err)
    }

    // Get the Wi-Fi adapter IP address
    wifiIP := network_interface.GetWiFiIP()
    if wifiIP == "" {
        fmt.Println("Could not find Wi-Fi IP address")
        return
    }

    // Define the "videos" folder path
    videosFolderPath := filepath.Join("videos")

    // Ensure "videos" folder exists
    if err := ui.CheckAndCreateFolder(videosFolderPath); err != nil {
        fmt.Println("Error creating videos folder:", err)
        return
    }

    // Generate the index.html file
    if err := ui.GenerateIndexHTML(videosFolderPath, wifiIP); err != nil {
        fmt.Println("Error generating index.html:", err)
        return
    }

    // Start the file server in a separate goroutine
    go file_server.StartFileServer()

    // Wait a bit before advertising mDNS to ensure server starts first
    go func() {
        time.Sleep(2 * time.Second)
        mdns.AdvertiseServer(wifiIP) // Use Wi-Fi IP
    }()

    // Keep the main function running
    select {} // Keeps the program alive
}

file_server.go

package file_server

import (
    "fmt"
    "log"
    "net/http"
    "os"
    "path/filepath"
    "video-server/auth"
    "video-server/network_interface"
)

// StartFileServer serves video files from the "videos" folder with authentication
func StartFileServer() {
    // Get the current working directory
    rootDir, err := os.Getwd()
    if err != nil {
        log.Fatalf("Failed to get working directory: %v", err)
    }

    // Define the videos folder path
    videosFolderPath := filepath.Join(rootDir, "videos")

    // Ensure the "videos" folder exists
    if _, err := os.Stat(videosFolderPath); os.IsNotExist(err) {
        err = os.Mkdir(videosFolderPath, os.ModePerm)
        if err != nil {
            log.Fatalf("Failed to create videos folder: %v", err)
        }
        fmt.Println("Created 'videos' folder at:", videosFolderPath)
    } else {
        fmt.Println("Using existing 'videos' folder at:", videosFolderPath)
    }

    // Get the IP address of the Wi-Fi adapter
    wifiIP := network_interface.GetWiFiIP()
    if wifiIP == "" {
        log.Fatal("Could not find Wi-Fi IP address")
    } else {
        fmt.Println("Device Wi-Fi IP address successfully obtained:", wifiIP)
    }

    // Bind the server to all interfaces (0.0.0.0) for broader accessibility
    address := "0.0.0.0:8080"
    fmt.Println("Starting file server on " + address + "/videos")

    // Serve the videos folder with authentication
    fileHandler := auth.BasicAuth(http.StripPrefix("/videos/", http.FileServer(http.Dir(videosFolderPath))))

    // Start the HTTP server directly without ServeMux
    err = http.ListenAndServe(address, fileHandler)
    if err != nil {
        log.Fatal("Error starting file server:", err)
    }
}

mdns.go

package mdns

import (
    "fmt"
    "log"
    "time"

    "github/grandcat/zeroconf"
)

// AdvertiseServer advertises the server using mDNS
func AdvertiseServer(wifiIP string) {
    if wifiIP == "" {
        log.Println("Could not find Wi-Fi IP address, skipping mDNS advertisement.")
        return
    }

    // Register the mDNS service
    service, err := zeroconf.Register(
        "WiFi File Server", // Service Name
        "_http._tcp",       // Service Type (HTTP over TCP)
        "local.",           // mDNS Domain (Fixed)
        8080,               // Port
        []string{
            "txtvers=1",
            "path=/videos/",
            "ip=" + wifiIP, // ✅ Explicitly advertise the Wi-Fi IP
        },
        nil, // No need for custom interfaces
    )
    if err != nil {
        log.Println("Error advertising mDNS service:", err)
        return
    }
    defer service.Shutdown() // Keep mDNS running until the program exits

    fmt.Println("mDNS Service is running. Try: http://" + wifiIP + ":8080/videos/")

    // Keep the service running
    for {
        time.Sleep(10 * time.Second) // Keep alive
    }
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744109381a4558878.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信