123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- package main
- import (
- "flag"
- "html/template"
- "log"
- "net/http"
- "strings"
- )
- const (
- shortenPath = "/s/"
- decodePath = "/d/"
- )
- var host = flag.String("h", "localhost", "Host on which to serve")
- var port = flag.String("p", "9090", "Port on which to serve")
- var file = flag.String("f", "links.txt", "File to which save links")
- var domain = flag.String("d", "", "Domain of shorty, preferably add schema")
- var toSave chan string
- func init() {
- toSave = make(chan string, 100)
- }
- func shorten(w http.ResponseWriter, r *http.Request) {
- link := r.URL.Query().Get("link")
- if link == "" {
- link = strings.TrimPrefix(r.URL.Path, shortenPath)
- }
- linkID := addLink(link, toSave)
- t := template.Must(template.ParseFiles("./html/result.html"))
- shortened := r.Host + "/" + linkID
- if *domain != "" {
- shortened = *domain + "/" + linkID
- }
- t.Execute(w, shortened)
- }
- func decode(w http.ResponseWriter, r *http.Request) {
- link := r.URL.Query().Get("link")
- if link == "" {
- link = strings.TrimPrefix(r.URL.Path, shortenPath)
- }
- t := template.Must(template.ParseFiles("./html/result.html"))
- parts := strings.Split(link, "/")
- linkID := parts[len(parts)-1]
- if linkID != "" {
- fullLink := getLink(linkID)
- if fullLink != "" {
- t.Execute(w, fullLink)
- return
- }
- }
- t.Execute(w, "Not found!")
- }
- func serveIndex(w http.ResponseWriter, r *http.Request) {
- t := template.Must(template.ParseFiles("./html/index.html"))
- t.Execute(w, nil)
- }
- func redirectOrServe(w http.ResponseWriter, r *http.Request) {
- linkID := strings.TrimPrefix(r.URL.Path, "/")
- if linkID == "" {
- serveIndex(w, r)
- } else {
- link := getLink(linkID)
- if link != "" {
- http.Redirect(w, r, link, http.StatusMovedPermanently)
- } else {
- serveIndex(w, r)
- }
- }
- }
- func main() {
- flag.Parse()
- readLinks(*file)
- go saveLink(*file, toSave)
- hostname := *host + ":" + *port
- http.HandleFunc(shortenPath, shorten)
- http.HandleFunc(decodePath, decode)
- http.HandleFunc("/", redirectOrServe)
- log.Fatal(http.ListenAndServe(hostname, nil))
- }
|