Browse Source

优化项目结构

liuyuqi-dellpc 1 year ago
parent
commit
df954747b7
3 changed files with 52 additions and 50 deletions
  1. 1 1
      go.mod
  2. 23 38
      main.go
  3. 28 11
      util/web.go

+ 1 - 1
go.mod

@@ -1,3 +1,3 @@
-module github.com/klipitkas/fs-go
+module github.com/jianboy/fs-go
 
 go 1.13

+ 23 - 38
main.go

@@ -3,11 +3,9 @@ package main
 import (
 	"flag"
 	"fmt"
-	"github.com/klipitkas/fs-go/util"
+	"github.com/jianboy/fs-go/util"
 	"log"
-	"net"
 	"net/http"
-	"os/exec"
 	"strconv"
 )
 
@@ -15,19 +13,17 @@ var port int
 var dir string
 
 func main() {
-
+	banner()
 	// Handle the flags that are provided.
 	flag.IntVar(&port, "port", 8080, "The port that the server will listen to.")
 	flag.StringVar(&dir, "dir", ".", "The root directory that will be served.")
 	// Parse the flags.
 	flag.Parse()
 
-	// Create the fileserver.
-	fs := http.FileServer(http.Dir(dir))
 	log.Printf("server is start %v: %v", port, dir)
 	//check port
 	// for i := 0; i < 5; i++ {
-	// 	if checkAvailablePort(port) {
+	// 	if util.checkAvailablePort(port) {
 	// 		break
 	// 	} else {
 	// 		// log.Println(strconv.Itoa(port) + " is not available.")
@@ -36,49 +32,38 @@ func main() {
 	// 	}
 	// }
 
-	// Start the file server.
+	go util.OpenBrowser("http://localhost:" + strconv.Itoa(port)) // Open browser in a goroutine
+
 	err := http.ListenAndServe(":"+fmt.Sprintf("%d", port), http.HandlerFunc(handler))
 	if err != nil {
 		log.Fatal("server error on port %v: %v", port, err)
 
 	}
 	log.Printf("Server started on port %d\n", port)
-	
-	// open browser
-	l, err := net.Listen("tcp", "localhost:"+strconv.Itoa(port))
-	if err != nil {
-		log.Fatal(err)
-	}
-	err = util.OpenUrl("http://localhost:" + strconv.Itoa(port))
-	if err != nil {
-		log.Fatal(err)
-	}
-	log.Fatal(http.Serve(l, fs))
+}
+
+func banner() {
+	fmt.Println(`
+                   _______  _______         _______  _______ 
+                  (  ____ \(  ____ \       (  ____ \(  ___  )
+                  | (    \/| (    \/       | (    \/| (   ) |
+                  | (__    | (_____  _____ | |      | |   | |
+                  |  __)   (_____  )(_____)| | ____ | |   | |
+                  | (            ) |       | | \_  )| |   | |
+                  | )      /\____) |       | (___) || (___) |
+                  |/       \_______)       (_______)(_______)
+			author: liuyuqi.gov@msn.cn
+	`)
 }
 
 // remove header cache
 func handler(w http.ResponseWriter, r *http.Request) {
-    w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") // HTTP 1.1.
-    w.Header().Set("Pragma", "no-cache") // HTTP 1.0.
-    w.Header().Set("Expires", "0") // Proxies.
-    
+	w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") // HTTP 1.1.
+	w.Header().Set("Pragma", "no-cache")                                   // HTTP 1.0.
+	w.Header().Set("Expires", "0")                                         // Proxies.
+
 	if r.URL.Path == "/favicon.ico" {
 		return
 	}
 	http.StripPrefix("/", http.FileServer(http.Dir(dir))).ServeHTTP(w, r)
 }
-
-//checkAvailablePort 端口可用检测,netstat 只适合linux
-func checkAvailablePort(port int) (res bool) {
-    checkStatement := fmt.Sprintf(`lsof -i:%d -t`, port)
-    output, err := exec.Command("sh", "-c", checkStatement).Output()
-    if err != nil {
-        return false
-    }
-
-    if len(output) > 0 {
-        return false
-    }
-
-    return true
-}

+ 28 - 11
util/web.go

@@ -5,18 +5,35 @@ import (
 	"os/exec"
 	"runtime"
 )
-var commonds = map[string]string{
-	"windows": "cmd /c start",
-	"darwin":  "open",
-	"linux":   "xdg-open",
+
+func OpenBrowser(url string) error {
+	var err error
+
+	switch runtime.GOOS {
+	case "linux":
+		err = exec.Command("xdg-open", url).Start()
+	case "windows":
+		err = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
+	case "darwin":
+		err = exec.Command("open", url).Start()
+	default:
+		err = fmt.Errorf("unsupported platform")
+	}
+
+	return err
 }
 
-//OpenUrl 调用系统命令打开浏览器
-func OpenUrl(url string) error {
-	run, ok := commonds[runtime.GOOS]
-	if !ok {
-		return fmt.Errorf("don't know how to open things on %s platform", runtime.GOOS)
+// checkAvailablePort 端口可用检测,netstat 只适合linux
+func checkAvailablePort(port int) (res bool) {
+	checkStatement := fmt.Sprintf(`lsof -i:%d -t`, port)
+	output, err := exec.Command("sh", "-c", checkStatement).Output()
+	if err != nil {
+		return false
 	}
-	cmd := exec.Command(run, url)  //拼凑命令: cmd /c start https://baidu.com
-	return cmd.Start()
+
+	if len(output) > 0 {
+		return false
+	}
+
+	return true
 }