server.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package main
  2. import (
  3. "flag"
  4. "html/template"
  5. "log"
  6. "net/http"
  7. "strings"
  8. )
  9. const (
  10. shortenPath = "/s/"
  11. decodePath = "/d/"
  12. indexHTML = "./html/index.html"
  13. )
  14. var host = flag.String("h", "localhost", "Host on which to serve")
  15. var port = flag.String("p", "9090", "Port on which to serve")
  16. var file = flag.String("f", "links.txt", "File to which save links")
  17. var domain = flag.String("d", "", "Domain of shorty, preferably add schema")
  18. var toSave chan string
  19. func init() {
  20. toSave = make(chan string, 100)
  21. }
  22. func shorten(w http.ResponseWriter, r *http.Request) {
  23. link := r.URL.Query().Get("link")
  24. if link == "" {
  25. link = strings.TrimPrefix(r.URL.Path, shortenPath)
  26. }
  27. linkID := addLink(link, toSave)
  28. t := template.Must(template.ParseFiles("./html/result.html"))
  29. shortened := r.Host + "/" + linkID
  30. if *domain != "" {
  31. shortened = *domain + "/" + linkID
  32. }
  33. t.Execute(w, shortened)
  34. }
  35. func decode(w http.ResponseWriter, r *http.Request) {
  36. link := r.URL.Query().Get("link")
  37. if link == "" {
  38. link = strings.TrimPrefix(r.URL.Path, shortenPath)
  39. }
  40. t := template.Must(template.ParseFiles("./html/result.html"))
  41. parts := strings.Split(link, "/")
  42. linkID := parts[len(parts)-1]
  43. if linkID != "" {
  44. fullLink := getLink(linkID)
  45. if fullLink != "" {
  46. t.Execute(w, fullLink)
  47. return
  48. }
  49. }
  50. t.Execute(w, "Not found!")
  51. }
  52. func redirectOrServe(w http.ResponseWriter, r *http.Request) {
  53. linkID := strings.TrimPrefix(r.URL.Path, "/")
  54. if linkID != "" {
  55. link := getLink(linkID)
  56. if link != "" {
  57. http.Redirect(w, r, link, http.StatusMovedPermanently)
  58. return
  59. }
  60. }
  61. http.ServeFile(w, r, indexHTML)
  62. }
  63. func main() {
  64. flag.Parse()
  65. readLinks(*file)
  66. go saveLink(*file, toSave)
  67. hostname := *host + ":" + *port
  68. http.HandleFunc(shortenPath, shorten)
  69. http.HandleFunc(decodePath, decode)
  70. http.HandleFunc("/", redirectOrServe)
  71. log.Fatal(http.ListenAndServe(hostname, nil))
  72. }