package main import ( "net/http" "fmt" "log" "html/template" "github.com/kreativmonkey/shrt/lib" ) type Page struct { 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) { fmt.Println("method: ", r.Method) //get request method fmt.Println("Path: ", r.URL.Path[1:]) switch r.Method { case "GET": var redirect string if ok := short.Get(r.URL.Path[1:], &redirect); ok{ P := Page{Title: ToString(r.URL.Path[1:]), Body: redirect} fmt.Printf("Redirect: %s \n", redirect) t, _ := template.ParseFiles("template/index.gohtml") t.Execute(w, P) fmt.Println("Url by Token:", P) } else { t, _ := template.ParseFiles("template/index.gohtml") t.Execute(w, nil) } case "POST": r.ParseForm() var test string token, err := short.Add(ToString(r.Form["url"]), &test) if err != nil { panic(err) } P := Page{Title: ToString(r.Form["url"]), Body: token} t, _ := template.ParseFiles("template/index.gohtml") t.Execute(w, P) fmt.Println("Token by Url:", P) } } func handelPost(w http.ResponseWriter, r *http.Request){ } func main() { http.HandleFunc("/", index) // setting router rule err := http.ListenAndServe(":9090", nil) // setting listening port if err != nil { log.Fatal("ListenAndServe: ", err) } } // ToString convert the input to a string. func ToString(obj interface{}) string { res := fmt.Sprintf("%s", obj) return string(res) }