~ols/dns-url-shortener

dns-url-shortener/main.go -rw-r--r-- 1.4 KiB
4c5572b1Oliver Leaver-Smith Initial commit 2 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package main

import (
	"context"
	"log"
	"net"
	"net/http"
	"net/url"
	"os"
	"time"

	"github.com/gorilla/mux"
)

const timeout = 1 * time.Second

var attemptForward = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	baseDomain := os.Getenv("BASE_DOMAIN")
	vars := mux.Vars(r)
	slug := vars["shortcode"]
	domain := slug + "." + baseDomain
	ctx, cancel := context.WithTimeout(context.TODO(), timeout)
	defer cancel()
	var res net.Resolver
	txtRecords, err := res.LookupTXT(ctx, domain)
	if err != nil {
		log.Printf("No TXT records found: %s", err)
		w.Write([]byte("No entry found for that short code"))
		return
	}
	redirect := txtRecords[0]
	if len(txtRecords) > 0 {
		isUrl := IsUrl(redirect)
		if !isUrl {
			log.Printf("Provided forward (%s) is not a URL", redirect)
			w.Write([]byte("No entry found for that short code"))
			return
		}
		log.Printf("Matching entry found for %s, redirecting to %s", slug, redirect)
		http.Redirect(w, r, redirect, 302)
	} else {
		log.Printf("No entry found for %s", slug)
		w.Write([]byte("No entry found for that short code"))
	}

})

func IsUrl(str string) bool {
	// We do this because url.ParseRequestURI now says
	// that a relative URL like /cabbage.html is legit
	u, err := url.Parse(str)
	return err == nil && u.Scheme != "" && u.Host != ""
}

func main() {
	r := mux.NewRouter()
	r.Handle("/{shortcode}", attemptForward).Methods("GET")
	http.ListenAndServe(":"+os.Getenv("PORT"), r)
}