package main import ( "net/http" "encoding/json" "fmt" "text/template" "net/url" "github.com/kreativmonkey/shrt/shrty" ) type Page struct { Host string Title string Body string } // Load the main Page with an Imput field for the URL to short. func index(w http.ResponseWriter, r *http.Request) { t, _ := template.ParseFiles("template/index.gohtml") t.Execute(w, Page{ Host: config.Host, Title: config.Title, }) } // Redirect to the URL behind the requested token. func redirect(w http.ResponseWriter, r *http.Request){ 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 { http.Redirect(w, r, "/", 301) } } // func shorten(w http.ResponseWriter, r *http.Request){ var token string err := short.Short(r.FormValue("url"), &token) if err != nil { panic(err) } P := Page{Title: "Url:", Body: r.Host + "/" + token} t, _ := template.ParseFiles("template/short.gohtml") t.Execute(w, P) } // GET: http://example.com/api/action/shorten?key=API_KEY_HERE&url=https://google.com&custom_ending=CUSTOM_ENDING // Response: {"action": "shorten","result": "https://example.com/5kq"} func shortenJSON(w http.ResponseWriter, r *http.Request){ query := r.URL.Query() queryu, err := url.QueryUnescape(query.Get("url")) check(err) var token string err = short.Short(queryu, &token) check(err) respond := response{ Action: "shorten", Result: r.Host + "/" + token, } w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(http.StatusOK) if err := json.NewEncoder(w).Encode(&respond); err != nil { panic(err) } } // GET: http://example.com/api/action/lookup?key=API_KEY_HERE&url_ending=5kq // Response: {"action":"lookup","result": {"long_url": "https:\/\/google.com","created_at": {"date":"2016-02-12 15:20:34.000000","timezone_type":3,"timezone":"UTC"},"clicks":"0"}} func lookupJSON(w http.ResponseWriter, r *http.Request){ query := r.URL.Query() queryu, err := url.QueryUnescape(query.Get("url_ending")) check(err) var result shrty.Data var respond response if ok := short.GetAPI(queryu, &result); ok { respond := response{ Action: "lookup", Result: result, } w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(http.StatusOK) if err := json.NewEncoder(w).Encode(&respond); err != nil { panic(err) } } else { w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(http.StatusNotFound) if err := json.NewEncoder(w).Encode(&respond); err != nil { panic(err) } } } func all(w http.ResponseWriter, r *http.Request){ t, _ := template.New("all").Parse("{{.}}") t.Execute(w, short.All()) } func check(err error) { if err != nil { panic(err) } }