Created
July 27, 2020 20:52
-
-
Save drewtempelmeyer/332fb51d2f4cd5ff55d7b6a4a9888131 to your computer and use it in GitHub Desktop.
super simple url shortener #golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"encoding/json" | |
"fmt" | |
"io" | |
"log" | |
"net/http" | |
"os" | |
"strings" | |
"time" | |
"github.com/go-redis/redis/v8" | |
"github.com/gorilla/mux" | |
"github.com/patrickmn/go-cache" | |
) | |
var cash *cache.Cache | |
var rdb *redis.Client | |
var ctx = context.Background() | |
type addResult struct { | |
ID string `json:"id"` | |
URL string `json:"url"` | |
} | |
func getEnv(key, fallback string) string { | |
if value, ok := os.LookupEnv(key); ok { | |
return value | |
} | |
return fallback | |
} | |
func getURL(key string) (string, error) { | |
if x, found := cash.Get(key); found { | |
return x.(string), nil | |
} | |
url, err := rdb.HGet(ctx, "links", key).Result() | |
if err != nil { | |
return "", err | |
} | |
cash.Set(key, url, cache.DefaultExpiration) | |
return url, nil | |
} | |
func authHandler(next http.Handler) http.HandlerFunc { | |
key := os.Getenv("API_TOKEN") | |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
auth := strings.SplitN(r.Header.Get("Authorization"), " ", 2) | |
if len(auth) != 2 || auth[0] != "Bearer" || auth[1] != key { | |
http.Error(w, "authorization failed", http.StatusUnauthorized) | |
return | |
} | |
next.ServeHTTP(w, r) | |
}) | |
} | |
func addHandler(w http.ResponseWriter, r *http.Request) { | |
if err := r.ParseForm(); err != nil { | |
log.Fatal(err) | |
fmt.Fprintf(w, "error parsing response: %v", err) | |
return | |
} | |
id := r.FormValue("id") | |
url := r.FormValue("url") | |
if len(url) == 0 || len(id) == 0 { | |
http.Error(w, "you must specifly a url and an id", http.StatusBadRequest) | |
return | |
} | |
if err := rdb.HSet(ctx, "links", []string{id, url}).Err(); err != nil { | |
log.Fatal(err) | |
http.Error(w, "error adding link", http.StatusBadRequest) | |
return | |
} | |
cash.Delete(id) | |
w.Header().Set("Content-Type", "application/json") | |
result, _ := json.Marshal(addResult{id, url}) | |
io.WriteString(w, string(result)) | |
} | |
func rootHandler(w http.ResponseWriter, r *http.Request) { | |
http.Redirect(w, r, getEnv("ROOT_REDIRECT", "https://dmt.sh"), 302) | |
} | |
func redirectHandler(w http.ResponseWriter, r *http.Request) { | |
vars := mux.Vars(r) | |
url, err := getURL(vars["id"]) | |
if err == nil && len(url) > 0 { | |
http.Redirect(w, r, url, 302) | |
return | |
} | |
http.Error(w, "not found", http.StatusNotFound) | |
} | |
func main() { | |
rdb = redis.NewClient(&redis.Options{ | |
Addr: getEnv("REDIS_HOST", "localhost:6379"), | |
Password: getEnv("REDIS_PASSWORD", ""), | |
DB: 0, | |
}) | |
cash = cache.New(5*time.Minute, 10*time.Minute) | |
r := mux.NewRouter() | |
r.HandleFunc("/", authHandler(http.HandlerFunc(addHandler))).Methods("POST") | |
r.HandleFunc("/{id}", redirectHandler).Methods("GET") | |
r.HandleFunc("/", rootHandler).Methods("GET") | |
http.Handle("/", r) | |
http.ListenAndServe(":8000", nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment