Skip to content

Instantly share code, notes, and snippets.

@matteosuppo
Created March 23, 2017 13:23
Show Gist options
  • Save matteosuppo/8e15f733cb3ecca465cb62239820b4b7 to your computer and use it in GitHub Desktop.
Save matteosuppo/8e15f733cb3ecca465cb62239820b4b7 to your computer and use it in GitHub Desktop.
A simple redirect manager
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
"github.com/alecthomas/template"
"github.com/pkg/errors"
)
// Redirects is a map backed up by a file
type Redirects map[string]string
func (r Redirects) Read() error {
file, err := ioutil.ReadFile("redirects.txt")
if err != nil {
return errors.Wrapf(err, "redirects read")
}
lines := strings.Split(string(file), "\n")
for _, line := range lines {
if line == "" {
continue
}
parts := strings.Split(line, " ")
if len(parts) != 2 {
return fmt.Errorf("redirects read: couldn't parse line '%s'", line)
}
r[parts[0]] = parts[1]
}
return nil
}
func (r Redirects) Write() error {
out := ""
for key, value := range r {
out = out + key + " " + value + "\n"
}
err := ioutil.WriteFile("redirects.txt", []byte(out), 0644)
if err != nil {
return errors.Wrapf(err, "redirects write")
}
return nil
}
func main() {
redirs := Redirects{}
err := redirs.Read()
if err != nil {
err = redirs.Write()
if err != nil {
panic(err.Error())
}
}
form := `<h1>Add redirects</h1>
<form method="post">
<input type="submit">
<table>
<tr><th>From</th><th>To</th></tr>
<tr><td><input type="text" name="key" value=""></td><td><input type="text" name="value" value=""></td></tr>
{{ range $key, $value := . }}
<tr><td><input type="text" name="key" value="{{ $key }}"></td><td><input type="text" name="value" value="{{ $value }}"></td></tr>
{{ end }}
</table>
</form>
`
t, err := template.New("form").Parse(form)
if err != nil {
panic(err.Error())
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if redir, ok := redirs[r.URL.Path]; ok {
http.Redirect(w, r, redir, 301)
return
}
http.NotFound(w, r)
})
http.HandleFunc("/redirect", func(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
if keys, ok := r.Form["key"]; ok {
if values, ok := r.Form["value"]; ok {
for i := range keys {
if keys[i] == "" || values[i] == "" {
continue
}
redirs[keys[i]] = values[i]
}
err := redirs.Write()
if err != nil {
log.Printf("%+v", err)
}
}
}
t.Execute(w, redirs)
})
http.ListenAndServe(":8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment