Golang sample code to implement the web file sharing service
- 2020-06-19 10:29:26
- OfStack
This article mainly introduces the Golang implementation web file sharing service sample code, to share with you, specific as follows:
Very simple, just two lines of code.
http.Handle("/", http.FileServer(http.Dir("./"))) // Treat the current file directory as a Shared directory
http.ListenAndServe(":8080", nil)
At this point, open http://ip address :8080 in your browser.
Maybe that's it, but for the convenience of non-programmer users, I also need the program to automatically get the local Intranet ip address, which the browser opens automatically.
Gets the Intranet ip address
func GetIntranetIp() (r []string) {
addrs, err := net.InterfaceAddrs()
if err != nil {
log.Fatal(err)
}
for _, address := range addrs {
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
r = append(r, ipnet.IP.String())
}
}
}
return
}
The native browser opens this address automatically
loclstr := fmt.Sprintf("http://%s:8080", ip address )
cmd := exec.Command("cmd", "/C", "start "+loclstr)
cmd.Run()
The complete code
package main
import (
"fmt"
"log"
"net"
"net/http"
"os/exec"
"time"
)
func main() {
address := GetIntranetIp()
fmt.Println(" This machine ip Address List: ")
for _, item := range address {
fmt.Println(item)
}
http.Handle("/", http.FileServer(http.Dir("./")))
fmt.Printf(" File sharing service open, monitor 8080 port \n Please open it in a browser :http://ip address :8080,eg:http://%s:8080\n Please do not close this program, have a good time \n", address[0])
go func() {
time.Sleep(2000)
loclstr := fmt.Sprintf("http://%s:8080", address[0])
cmd := exec.Command("cmd", "/C", "start "+loclstr)
cmd.Run()
}()
if err := http.ListenAndServe(":8080", nil); err != nil {
fmt.Println("err:", err)
}
}
func GetIntranetIp() (r []string) {
addrs, err := net.InterfaceAddrs()
if err != nil {
log.Fatal(err)
}
for _, address := range addrs {
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
r = append(r, ipnet.IP.String())
}
}
}
return
}