Skip to content

Instantly share code, notes, and snippets.

@justyns
Created September 14, 2015 13:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justyns/3dcbd3151acd6f693c7d to your computer and use it in GitHub Desktop.
Save justyns/3dcbd3151acd6f693c7d to your computer and use it in GitHub Desktop.
Simple Go URL Shortener. No persistence, just stores everything in memory.
package main
import (
"fmt"
"net/http"
"strconv"
)
type ShortURL struct {
ID uint64
URL string
Hits uint64
}
var shortURLs map[string]ShortURL
var lastID uint64
func redirectHandler(w http.ResponseWriter, r *http.Request) {
prefix := "/tyn"
if len(r.URL.Path) > len(prefix) {
shortCode := r.URL.Path[len(prefix):]
if shortURL, ok := shortURLs[shortCode]; ok {
// fmt.Fprintf(w, "%s -> %v", shortCode, shortURL)
http.Redirect(w, r, shortURL.URL, 301)
} else {
http.NotFound(w, r)
}
} else {
fmt.Fprintf(w, "HELLO!")
}
}
func newURLHandler(w http.ResponseWriter, r *http.Request) {
// newURL := r.URL.Path[len("/new/"):]
newURL := r.FormValue("url")
lastID++
newShortURL := ShortURL{lastID, newURL, 0}
newHash := strconv.FormatUint(lastID*3, 36)
shortURLs[newHash] = newShortURL
fmt.Fprintf(w, "New url: %v", newShortURL)
fmt.Fprintf(w, "New hash: %s", newHash)
}
func allURLsHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "All urls: %v", shortURLs)
}
func main() {
shortURLs = make(map[string]ShortURL)
lastID = 1500
http.HandleFunc("/", redirectHandler)
http.HandleFunc("/new/", newURLHandler)
http.HandleFunc("/all/", allURLsHandler)
http.ListenAndServe(":8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment