package main import ( "net/http" "encoding/json" "fmt" "text/template" "net/url" shorty "github.com/kreativmonkey/shrt/short" ) type Page struct { Host string Title string Body string } type response struct { Action string `json:"action"` Result interface{} `json:"result"` } // 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{Title: "Shrt"}) } // 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 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/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 test string err = short.Short(queryu, &test) check(err) respond := response{ Action: "shorten", Result: r.Host + "/" + test, } 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 shorty.Shrt var respond response if ok := short.GetAPI(queryu, &result); ok { respond := response{ Action: "shorten", 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) } }