main.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package main
  2. import (
  3. "battlecamp-go/board"
  4. "flag"
  5. "fmt"
  6. "log"
  7. "net"
  8. "net/http"
  9. "os"
  10. "runtime/pprof"
  11. "strconv"
  12. "golang.org/x/net/netutil"
  13. )
  14. var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
  15. func main() {
  16. fmt.Println("Board generator version 0.1")
  17. logFile, err := os.Create("server.log")
  18. if err == nil {
  19. log.SetOutput(logFile)
  20. } else {
  21. log.Println("ERROR: Cannot open log file, using console.")
  22. log.Printf("%v=n", err)
  23. }
  24. initCpuProfiler()
  25. http.HandleFunc("/", gzipHandler(generateBoard))
  26. http.HandleFunc("/status", status)
  27. http.HandleFunc("/debug/profiledump", profileDump)
  28. l, _ := net.Listen("tcp", ":8081")
  29. limitListerer := netutil.LimitListener(l, 100)
  30. log.Fatal(http.Serve(limitListerer, nil))
  31. }
  32. func generateBoard(w http.ResponseWriter, r *http.Request) {
  33. x, _ := strconv.Atoi(r.FormValue("x"))
  34. y, _ := strconv.Atoi(r.FormValue("y"))
  35. width, _ := strconv.Atoi(r.FormValue("width"))
  36. height, _ := strconv.Atoi(r.FormValue("height"))
  37. totalWidth, _ := strconv.Atoi(r.FormValue("totalWidth"))
  38. totalHeight, _ := strconv.Atoi(r.FormValue("totalHeight"))
  39. log.Printf("Creating partial x=%v, y=%v, width=%v, height=%v, totalWidth=%v, totalHeight=%v", x, y, width, height, totalWidth, totalHeight)
  40. b := board.NewRegion(x, y, width, height, totalWidth, totalHeight)
  41. b.WriteData(w)
  42. }
  43. func status(w http.ResponseWriter, r *http.Request) {
  44. w.Write([]byte("ok"))
  45. }
  46. func profileDump(w http.ResponseWriter, req *http.Request) {
  47. log.Println("Dumping cpu profile")
  48. pprof.StopCPUProfile()
  49. }
  50. func initCpuProfiler() {
  51. flag.Parse()
  52. if *cpuprofile != "" {
  53. f, err := os.Create(*cpuprofile)
  54. if err != nil {
  55. log.Printf("ERROR: %v\n", err)
  56. } else {
  57. pprof.StartCPUProfile(f)
  58. }
  59. }
  60. }