Esempio n. 1
0
File: api.go Progetto: gayanch/gourl
func Api(w http.ResponseWriter, r *http.Request) {
	fmt.Println(r.Method, r.URL, time.Now())

	r.ParseForm()
	if len(r.Form) != 2 {
		fmt.Fprintf(w, INVALID_REQUEST)
	} else {
		api := r.Form["api"][0]
		switch api {
		case "short":
			longurl := r.Form["url"][0]
			shorturl, _ := manager.SaveUrl(longurl)
			fmt.Fprintf(w, "{response: '%s'}", shorturl)

		case "long":
			shorturl := r.Form["url"][0]
			if longurl, err := manager.ReadUrl(shorturl); err == nil {
				fmt.Fprintf(w, "{response: '%s'}", longurl)
			} else {
				fmt.Fprintf(w, INVALID_REQUEST)
			}
		default:
			fmt.Fprintf(w, INVALID_REQUEST)
		}
	}
}
Esempio n. 2
0
File: home.go Progetto: asce4s/gourl
func Home(w http.ResponseWriter, r *http.Request) {
	fmt.Println(r.Method, r.URL)
	if r.Method == "GET" {
		if len(r.URL.Path) == 1 {
			//no short url, serve home
			t, _ := template.ParseFiles("template/home.html")
			t.ExecuteTemplate(w, t.Name(), nil)
		} else {
			//short url provided, redirect
			shorturl := r.URL.Path[len("/"):]
			if longurl, err := manager.ReadUrl(shorturl); err == nil {
				http.Redirect(w, r, longurl, 303)
			} else {
				fmt.Fprintf(w, "Invalid short url")
			}

		}
	} else {
		r.ParseForm()
		longurl := r.Form["longurl"][0]

		//check whether http:// is present in address
		//it is required in order to work redirect correctly
		if longurl[:len("http://")] != "http://" {
			longurl = "http://" + longurl
		}

		if shorturl, err := manager.SaveUrl(longurl); err == nil {
			fmt.Fprintf(w, "%s/%s", SITE_ADDRESS, shorturl)
		} else {
			fmt.Fprintf(w, "Error generating url")
		}
	}

}
Esempio n. 3
0
func Home(w http.ResponseWriter, r *http.Request) {
	fmt.Println(r.Method, r.URL, time.Now())

	//GET resuest, serve homepage
	if r.Method == "GET" {
		if len(r.URL.Path) == 1 {
			//no short url, serve home
			t, _ := template.ParseFiles("template/home.html")
			t.ExecuteTemplate(w, t.Name(), nil)

		} else {
			//short url provided, redirect
			shorturl := r.URL.Path[len("/"):]
			if longurl, err := manager.ReadUrl(shorturl); err == nil {
				http.Redirect(w, r, longurl, 303)

				//update analytics
				analytics.Update(shorturl)
			} else {
				//given shorturl is not found, redirect to homepage
				http.Redirect(w, r, "/", 303)
			}
		}

	} else {
		//POST request, generate shorturl from given longurl and return
		r.ParseForm()
		longurl := r.Form["longurl"][0]

		if shorturl, err := manager.SaveUrl(longurl); err == nil {
			fmt.Fprintf(w, "<a href='/%s'>%s</a>", shorturl, shorturl)

		} else {
			fmt.Fprintf(w, "Error generating URL")
		}
	}
}