admin管理员组

文章数量:1394989

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
    }
}

本文标签: web servicesWhy is my video file server written in GO not broadcasting over the WIFI networkStack Overflow