package main import ( "net/http" "fmt" "text/template" "github.com/kreativmonkey/shrt/short" "log" ) 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": 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 { P := Page{Title: "All: ", Body: short.All ()} t, _ := template.ParseFiles("template/index.gohtml") t.Execute(w, P) } case "POST": var test string token, err := short.Add(r.FormValue("url"), &test) if err != nil { panic(err) } P := Page{Title: r.FormValue("url"), Body: token} t, _ := template.ParseFiles("template/index.gohtml") t.Execute(w, P) fmt.Println("Token by Url:", P) } } func main() { http.HandleFunc("/", index) // setting router rule err := http.ListenAndServe(":9090", nil) // setting listening port if err != nil { log.Fatal("ListenAndServe: ", err) } }