Skip to content

Instantly share code, notes, and snippets.

@phbits
Last active December 1, 2021 14:51
Show Gist options
  • Save phbits/fd770ecbb623ae6ec89c7b1d72ac037a to your computer and use it in GitHub Desktop.
Save phbits/fd770ecbb623ae6ec89c7b1d72ac037a to your computer and use it in GitHub Desktop.
Simple URL Shortening Service
package main
import (
"flag"
"log"
"io/ioutil"
"encoding/json"
"net/http"
"regexp"
)
// global variables
var (
redirectMap = make(map[string]string)
defaultRedirect = ""
)
func check(e error) {
if e != nil {
panic(e)
}
}
func handler(w http.ResponseWriter, r *http.Request) {
// set redirect destination to the default
newLocation := defaultRedirect
// regex is used to sanitize URL paths.
// consider updating to allow more characters or URLs longer than 15
// each shortened URL must match the regex specified here
match,_ := regexp.MatchString("^/[a-zA-Z0-9]{1,15}$", r.URL.Path)
// check if regex matches
if match {
// check map for redirect
if value, ok := redirectMap[r.URL.Path]; ok {
// redirect found. Update variable with new destination
newLocation = value
}
}
// http redirect response
http.Redirect(w, r, newLocation, http.StatusFound)
}
func main() {
// define cmd switches and set defaults
confPtr := flag.String("conf","redirects.json","a string")
listenOnPtr := flag.String("listenOn","127.0.0.1:8090","a string")
defaultRedirectPtr := flag.String("defaultRedirect","https://defaultRedirect.domain.local/","a string")
// parse cmd switches
flag.Parse()
// set default redirect global variable
defaultRedirect = *defaultRedirectPtr
// parse json conf
jsonFile, err := ioutil.ReadFile(*confPtr)
check(err)
// store json conf data in global variable
err = json.Unmarshal(jsonFile, &redirectMap)
check(err)
// establish http svc
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe(*listenOnPtr, nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment