package main
import (
"flag"
"fmt"
"html/template"
"log"
"math/rand"
"net"
"os"
"strings"
"time"
"github.com/valyala/fasthttp"
"github.com/wolviecb/short/shortie"
"github.com/asaskevich/govalidator"
"github.com/fasthttp/router"
"github.com/patrickmn/go-cache"
)
const (
letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" // Base strings for randStringBytesMaskImprSrc
letterIdxBits = 6 // 6 bits to represent a letter index
letterIdxMask = 1< 65535 || *port < 1 {
log.Fatalln("Invalid port number")
}
shortie.Port = *port
if *path != "" && !strings.HasSuffix(*path, "/") {
*path = *path + "/"
}
shortie.Path = *path
ip := net.ParseIP(*addr)
if ip != nil {
listenAddr = fmt.Sprintf("%s:%v", ip.String(), *port)
} else {
if govalidator.IsDNSName(*addr) {
listenAddr = fmt.Sprintf("%s:%v", *addr, *port)
} else {
log.Fatalln("Invalid ip address")
}
}
if !govalidator.IsDNSName(*domain) {
log.Fatalln("Invalid domain address")
}
if *http {
shortie.Proto = "http"
}
shortie.Domain = *domain
shortie.Exp = time.Duration(*exp) * time.Hour
shortie.Cleanup = time.Duration(*cleanup) * time.Hour
shortie.Pool = cache.New(shortie.Exp, shortie.Cleanup)
t := template.Must(template.ParseFiles("templates/response.html"))
r := router.New()
r.GET("/", shortie.IndexHandler(t))
r.POST("/", shortie.Short(t))
r.GET("/{key}", shortie.Redir(t))
r.GET("/v1/toFile", shortie.ToFile(t))
r.GET("/v1/fromFile", shortie.FromFile(t))
r.GET("/v1/count", func(ctx *fasthttp.RequestCtx) { fmt.Fprintf(ctx, "%v", shortie.Pool.ItemCount()) })
r.GET("/v1/dump", shortie.Dump(t))
r.POST("/v1/fromPost", shortie.FromPost(t))
log.Printf("Domain: %s, URL Proto: %s, Listen Address: %s\n", shortie.Domain, shortie.Proto, listenAddr)
log.Fatal(fasthttp.ListenAndServe(":8080", logger(r.Handler)))
}