main.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "log"
  6. "net"
  7. "net/http"
  8. "os"
  9. "strings"
  10. "time"
  11. )
  12. var portFlag = flag.String("port", "12345", "server port")
  13. var genFlag = flag.Bool("gen", false, "HTML generation mode?")
  14. var themeFlag = flag.String("theme", "", "theme (dark | light)")
  15. var nobFlag = flag.Bool("nob", false, "not open browswer?")
  16. func main() {
  17. log.SetFlags(0)
  18. flag.Parse()
  19. port, isAppEngine := *portFlag, false
  20. if prt := os.Getenv("PORT"); prt != "" { // appengine std
  21. port = prt
  22. isAppEngine = true
  23. }
  24. addr, err := net.ResolveTCPAddr("tcp", fmt.Sprintf(":%v", port))
  25. if err != nil {
  26. log.Fatal(err)
  27. }
  28. Retry:
  29. l, err := net.ListenTCP("tcp", addr)
  30. if err != nil {
  31. if strings.Index(err.Error(), "bind: address already in use") >= 0 {
  32. addr.Port++
  33. if addr.Port < 65535 {
  34. goto Retry
  35. }
  36. }
  37. log.Fatal(err)
  38. }
  39. go101.theme = *themeFlag
  40. genMode, rootURL := *genFlag, fmt.Sprintf("http://localhost:%v/", addr.Port)
  41. if !genMode && !isAppEngine {
  42. if !*nobFlag {
  43. err = openBrowser(rootURL)
  44. if err != nil {
  45. log.Println(err)
  46. }
  47. }
  48. go updateGolang101()
  49. }
  50. runServer := func() {
  51. log.Println("Server started:")
  52. log.Printf(" http://localhost:%v (non-cached version)\n", addr.Port)
  53. log.Printf(" http://127.0.0.1:%v (cached version)\n", addr.Port)
  54. (&http.Server{
  55. Handler: go101,
  56. WriteTimeout: 10 * time.Second,
  57. ReadTimeout: 5 * time.Second,
  58. }).Serve(l)
  59. }
  60. if genMode {
  61. go runServer()
  62. genStaticFiles(rootURL)
  63. return
  64. }
  65. runServer()
  66. }