server.go 2.0 KB

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