You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
1.3 KiB
Go

package main
import (
"net/http"
"fmt"
"text/template"
"github.com/kreativmonkey/shrt/short"
"log"
)
type Page struct {
Host string
Title string
Body string
}
var (
short *shrt.Storage
)
func init() {
var err error
short, err = shrt.Open()
if err != nil {
panic(err)
}
}
func index(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
if redirect, ok := short.Get(r.URL.Path[1:]); ok{
http.Redirect(w, r, string(redirect), 301)
fmt.Printf("Token: %s Redirect to: %s \n", string(r.URL.Path[1:]), redirect)
} else {
t, _ := template.ParseFiles("template/index.gohtml")
t.Execute(w, Page{Title: "Shrt"})
}
case "POST":
var test string
token, err := short.Add(r.FormValue("url"), &test)
if err != nil {
panic(err)
}
P := Page{Title: "Url:", Body: r.Host + "/" + token}
t, _ := template.ParseFiles("template/index.gohtml")
t.Execute(w, P)
}
}
func all(w http.ResponseWriter, r *http.Request) {
t, _ := template.New("all").Parse("{{.}}")
t.Execute(w, short.All())
}
func main() {
http.HandleFunc("/", index) // setting router rule
http.HandleFunc("/all", all) // setting router rule
http.HandleFunc("/put", index) // setting router rule
err := http.ListenAndServe(":9090", nil) // setting listening port
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}