|
|
|
@ -27,8 +27,12 @@ func (handler *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
|
|
|
|
|
|
|
func (handler *Handler) HandleGet(w http.ResponseWriter, r *http.Request) { |
|
|
|
url := strings.Trim(r.URL.Path, "/") |
|
|
|
// If they gave us something like `/<shortcode>/<who knows>`
|
|
|
|
// then jst grab the first part
|
|
|
|
code := strings.SplitN(url, "/", 2)[0] |
|
|
|
value, ok := handler.cache.Get(code) |
|
|
|
|
|
|
|
// If the url exists in the cache and is a string, redirect to it
|
|
|
|
if ok { |
|
|
|
switch url := value.(type) { |
|
|
|
case string: |
|
|
|
@ -40,15 +44,29 @@ func (handler *Handler) HandleGet(w http.ResponseWriter, r *http.Request) { |
|
|
|
} |
|
|
|
|
|
|
|
func (handler *Handler) HandlePost(w http.ResponseWriter, r *http.Request) { |
|
|
|
// Parse url from body
|
|
|
|
reader := bufio.NewScanner(r.Body) |
|
|
|
reader.Scan() |
|
|
|
url, err := url.ParseRequestURI(reader.Text()) |
|
|
|
rawurl := reader.Text() |
|
|
|
|
|
|
|
// Ensure url given is a real url
|
|
|
|
cleanUrl, err := CleanURL(rawurl) |
|
|
|
if err != nil { |
|
|
|
panic(err) |
|
|
|
http.Error(w, fmt.Sprintf("Invalid url \"%s\"", reader.Text()), http.StatusBadRequest) |
|
|
|
return |
|
|
|
} |
|
|
|
|
|
|
|
// Generate short code and store in cache
|
|
|
|
code := GetShortCode([]byte(cleanUrl)) |
|
|
|
handler.cache.Add(code, cleanUrl) |
|
|
|
|
|
|
|
// Generate response url
|
|
|
|
codeUrl := &url.URL{ |
|
|
|
Scheme: "https", |
|
|
|
Host: r.Host, |
|
|
|
Path: "/" + code, |
|
|
|
} |
|
|
|
code := GetShortCode([]byte(url.String())) |
|
|
|
handler.cache.Add(code, url.String()) |
|
|
|
fmt.Fprintf(w, code) |
|
|
|
fmt.Fprintf(w, codeUrl.String()) |
|
|
|
} |
|
|
|
|
|
|
|
func NewServer(bind string, maxEntries int) *http.Server { |
|
|
|
|