a simple url shortener in Go (check it out at qurl.org)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
1.8 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "net"
  6. "net/http"
  7. "os"
  8. "qurl/pages"
  9. "qurl/static"
  10. "qurl/storage"
  11. "runtime"
  12. )
  13. //go:generate bindata -m Assets -r assets -p static -o static/assets.go assets
  14. func main() {
  15. dburl := flag.String("u", "bolt:./qurl.db", "url to database")
  16. lsaddr := flag.String("l", "127.0.0.1:8080", "listen address/port")
  17. jsonfile := flag.String("j", "", "path to json to load into database")
  18. maxpro := flag.Int("m", runtime.NumCPU()+2,
  19. "maximum number of threads to use")
  20. flag.Parse()
  21. if *maxpro < 3 {
  22. fmt.Fprintf(os.Stderr, "Thread limit too low: %d (min 3)\n", *maxpro)
  23. return
  24. }
  25. // Limit max processes
  26. runtime.GOMAXPROCS(*maxpro)
  27. // Open storage backend
  28. stor, err := storage.NewStorage(*dburl)
  29. if err != nil {
  30. fmt.Fprintf(os.Stderr, "Database connection error: %s\n", err.Error())
  31. return
  32. }
  33. defer stor.Shutdown()
  34. // Load data if asked
  35. if *jsonfile != "" {
  36. err := loadjson(stor, *jsonfile)
  37. if err != nil {
  38. fmt.Fprintf(os.Stderr, "%s\n", err.Error())
  39. return
  40. }
  41. }
  42. // Open listener port
  43. listen, err := net.Listen("tcp", *lsaddr)
  44. if err != nil {
  45. fmt.Fprintf(os.Stderr, "Listen error: %s\n", err.Error())
  46. return
  47. }
  48. mux := http.NewServeMux()
  49. mux.Handle("/index.html", &static.StaticContent{Content: "index.html"})
  50. mux.Handle("/favicon.ico", &static.StaticContent{Content: "favicon.ico"})
  51. mux.Handle("/qurl.css", &static.StaticContent{Content: "qurl.css"})
  52. submit := &pages.SubmitHandler{Storage: stor}
  53. err = submit.Init()
  54. if err != nil {
  55. fmt.Fprintf(os.Stderr, "Submit init error: %s\n", err.Error())
  56. return
  57. }
  58. mux.Handle("/submit.html", submit)
  59. fmt.Fprintf(os.Stdout, "qurl listening .. \n")
  60. err = http.Serve(listen, mux)
  61. if err != nil {
  62. fmt.Fprintf(os.Stderr, "Serve error: %s\n", err.Error())
  63. }
  64. }