main.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "github.com/klipitkas/fs-go/util"
  6. "log"
  7. "net"
  8. "net/http"
  9. "os/exec"
  10. "strconv"
  11. )
  12. var port int
  13. var dir string
  14. func main() {
  15. // Handle the flags that are provided.
  16. flag.IntVar(&port, "port", 8080, "The port that the server will listen to.")
  17. flag.StringVar(&dir, "dir", ".", "The root directory that will be served.")
  18. // Parse the flags.
  19. flag.Parse()
  20. // Create the fileserver.
  21. fs := http.FileServer(http.Dir(dir))
  22. log.Printf("server is start %v: %v", port, dir)
  23. //check port
  24. // for i := 0; i < 5; i++ {
  25. // if checkAvailablePort(port) {
  26. // break
  27. // } else {
  28. // // log.Println(strconv.Itoa(port) + " is not available.")
  29. // log.Printf("server error on port %v: %v", port, err)
  30. // port++
  31. // }
  32. // }
  33. // Start the file server.
  34. err := http.ListenAndServe(":"+fmt.Sprintf("%d", port), http.HandlerFunc(handler))
  35. if err != nil {
  36. log.Fatal("server error on port %v: %v", port, err)
  37. }
  38. log.Printf("Server started on port %d\n", port)
  39. // open browser
  40. l, err := net.Listen("tcp", "localhost:"+strconv.Itoa(port))
  41. if err != nil {
  42. log.Fatal(err)
  43. }
  44. err = util.OpenUrl("http://localhost:" + strconv.Itoa(port))
  45. if err != nil {
  46. log.Fatal(err)
  47. }
  48. log.Fatal(http.Serve(l, fs))
  49. }
  50. // remove header cache
  51. func handler(w http.ResponseWriter, r *http.Request) {
  52. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") // HTTP 1.1.
  53. w.Header().Set("Pragma", "no-cache") // HTTP 1.0.
  54. w.Header().Set("Expires", "0") // Proxies.
  55. if r.URL.Path == "/favicon.ico" {
  56. return
  57. }
  58. http.StripPrefix("/", http.FileServer(http.Dir(dir))).ServeHTTP(w, r)
  59. }
  60. //checkAvailablePort 端口可用检测,netstat 只适合linux
  61. func checkAvailablePort(port int) (res bool) {
  62. checkStatement := fmt.Sprintf(`lsof -i:%d -t`, port)
  63. output, err := exec.Command("sh", "-c", checkStatement).Output()
  64. if err != nil {
  65. return false
  66. }
  67. if len(output) > 0 {
  68. return false
  69. }
  70. return true
  71. }