Exemple #1
0
func ArticlePermaLinkHandler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	vars := mux.Vars(r)
	id, err := strconv.ParseInt(vars["id"], 10, 64)
	if err != nil {
		core.HandleError(c, w, err)
		return
	}

	article, err := GetArticleById(c, id, true)
	if err != nil {
		core.HandleNotFound(c, w)
		return
	}

	if !article.IsPublic {
		user := auth.CurrentUser(c)
		if !user.IsAdmin {
			core.HandleAuthRequired(c, w)
			return
		}
	}

	redirectTo, err := article.URL()
	if err != nil {
		core.HandleNotFound(c, w)
		return
	}
	http.Redirect(w, r, redirectTo.Path, 302)
}
Exemple #2
0
func ShowScoreHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	game, exists := games[vars["name"]]
	if !exists {
		http.Error(w, "Game doesn't exist", http.StatusBadRequest)
		return
	}
	gamescores, exists := scores[game]
	if !exists {
		http.Error(w, "Game doesn't have any scores", http.StatusBadRequest)
		return
	}
	if vars["id"] == "" {
		http.Error(w, "No score id specified", http.StatusBadRequest)
		return
	}
	id, err := strconv.Atoi(vars["id"])
	if err != nil {
		http.Error(w, "Score id should be a number", http.StatusBadRequest)
		return
	}
	score, exists := gamescores[id]
	if !exists {
		http.Error(w, "Game doesn't have score with that id", http.StatusBadRequest)
		return
	}
	response, _ := json.Marshal(score)
	fmt.Fprint(w, string(response))
}
Exemple #3
0
func shorten(w http.ResponseWriter, r *http.Request) {
	url := mux.Vars(r)["url"]

	log.Printf("Shorten %v\n", url)

	fmt.Fprintf(w, "Shortenize %v", url)
}
Exemple #4
0
func xhrSendHandler(r *Router, w http.ResponseWriter, req *http.Request) {
	if xhrProlog(w, req) {
		return
	}
	w.Header().Set("Content-type", "text/plain; charset=UTF-8")
	sessionId := mux.Vars(req)["sessionid"]
	// Find the session
	s := r.getSession(sessionId)
	if s == nil {
		http.NotFoundHandler().ServeHTTP(w, req)
		return
	}
	// Synchronization? What if an xhr request is still creating this?
	buf := bytes.NewBuffer(nil)
	io.Copy(buf, req.Body)
	req.Body.Close()
	if buf.Len() == 0 {
		http.Error(w, EmptyPayload.Error(), http.StatusInternalServerError)
		return
	}
	err := s.fromClient(message(buf.Bytes()))
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-length", "0")
	w.WriteHeader(http.StatusNoContent)
}
Exemple #5
0
func coffeeHandler(w http.ResponseWriter, req *http.Request) {
	filename := mux.Vars(req)["filename"]
	w.Header().Set("Cache-Control", "no-cache")
	filepath := path.Join(StaticDir, filename)

	stat, err := os.Stat(filepath)
	if err != nil {
		http.NotFound(w, req)
		return
	}
	// We may not have to do anything if the file hasn't changed. Taken from http package.
	mod := stat.ModTime()
	if !mod.IsZero() {
		t, err := time.Parse(http.TimeFormat, req.Header.Get("If-Modified-Since"))
		if err == nil && mod.Before(t.Add(1*time.Second)) {
			w.WriteHeader(http.StatusNotModified)
			return
		}
	}

	w.Header().Set("Content-type", "application/javascript")
	cmd := exec.Command("coffee", "-p", filepath)
	buffer := bytes.NewBuffer(nil)
	cmd.Stdout = buffer
	cmd.Stderr = os.Stderr
	err = cmd.Run()
	if err != nil {
		log.Print(err)
		http.Error(w, http.StatusText(500), 500)
		return
	}
	http.ServeContent(w, req, filename+".js", mod, bytes.NewReader(buffer.Bytes()))
}
Exemple #6
0
func ArticleDeleteHandler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	user := core.AdminUser(c, w)
	if user == nil {
		return
	}

	vars := mux.Vars(r)
	id, err := strconv.ParseInt(vars["id"], 10, 64)
	if err != nil {
		core.HandleError(c, w, err)
		return
	}

	article, err := GetArticleById(c, id, false)
	if err != nil {
		core.HandleNotFound(c, w)
		return
	}

	err = DeleteArticle(c, article)
	if err != nil {
		core.HandleError(c, w, err)
		return
	}

	http.Redirect(w, r, "/", 302)
}
Exemple #7
0
func AddGPSHandler(w http.ResponseWriter, r *http.Request) {
	// allow cross domain AJAX requests
	w.Header().Set("Access-Control-Allow-Origin", "http://pleskac.org")

	vars := mux.Vars(r)
	longStr := vars[longitude]
	latStr := vars[latitude]

	fmt.Println("Adding GPS location via webservice")

	longFlt, err := strconv.ParseFloat(longStr, 64)
	if err != nil {
		fmt.Println("Error parsing", longStr, "\n", err)
		return
	}

	latFlt, err := strconv.ParseFloat(latStr, 64)
	if err != nil {
		fmt.Println("Error parsing", latStr, "\n", err)
		return
	}

	standardType := vars[gpsType]
	if standardType != "OK" && standardType != "TRACK" {
		standardType = "TRACK"
	}

	//TODO: FIX THIS!!
	dblayer.AddGPSNow(longFlt, latFlt, "This was sent via iPhone, not SPOT.", standardType, "*****@*****.**")

	enc := json.NewEncoder(w)
	enc.Encode(standardType)
}
Exemple #8
0
func (this *context) XhrSendHandler(rw http.ResponseWriter, req *http.Request) {
	vars := mux.Vars(req)
	sessid := vars["sessionid"]
	if conn, exists := this.get(sessid); exists {
		data, err := ioutil.ReadAll(req.Body)
		if err != nil {
			rw.WriteHeader(http.StatusInternalServerError)
			fmt.Fprint(rw, err.Error())
			return
		}
		if len(data) < 2 {
			// see https://github.com/sockjs/sockjs-protocol/pull/62
			rw.WriteHeader(http.StatusInternalServerError)
			fmt.Fprint(rw, "Payload expected.")
			return
		}
		var a []interface{}
		if json.Unmarshal(data, &a) != nil {
			// see https://github.com/sockjs/sockjs-protocol/pull/62
			rw.WriteHeader(http.StatusInternalServerError)
			fmt.Fprint(rw, "Broken JSON encoding.")
			return
		}
		setCors(rw.Header(), req)
		setContentType(rw.Header(), "text/plain; charset=UTF-8")
		disableCache(rw.Header())
		conn.handleCookie(rw, req)
		rw.WriteHeader(http.StatusNoContent)
		go func() { conn.input_channel <- data }() // does not need to be extra routine?
	} else {
		rw.WriteHeader(http.StatusNotFound)
	}
}
Exemple #9
0
func followHandler(w http.ResponseWriter, r *http.Request) {
	println("follow")
	vars := mux.Vars(r)
	username := vars["username"]
	c := db.C("users")

	// 检查当前用户是否存在
	currUser, ok := currentUser(r)

	if !ok {
		http.Redirect(w, r, "/signin", http.StatusFound)
		return
	}

	user := User{}
	err := c.Find(bson.M{"username": username}).One(&user)

	if err != nil {
		message(w, r, "关注的会员未找到", "关注的会员未找到", "error")
		return
	}

	if user.IsFollowedBy(currUser.Username) {
		message(w, r, "你已经关注该会员", "你已经关注该会员", "error")
		return
	}
	c.Update(bson.M{"_id": user.Id_}, bson.M{"$push": bson.M{"fans": currUser.Username}})
	c.Update(bson.M{"_id": currUser.Id_}, bson.M{"$push": bson.M{"follow": user.Username}})

	http.Redirect(w, r, "/member/"+user.Username, http.StatusFound)
}
Exemple #10
0
func unfollowHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	username := vars["username"]
	c := db.C("users")

	// 检查当前用户是否存在
	currUser, ok := currentUser(r)

	if !ok {
		http.Redirect(w, r, "/", http.StatusFound)
		return
	}

	user := User{}
	err := c.Find(bson.M{"username": username}).One(&user)

	if err != nil {
		message(w, r, "没有该会员", "没有该会员", "error")
		return
	}

	if !user.IsFollowedBy(currUser.Username) {
		message(w, r, "不能取消关注", "该会员不是你的粉丝,不能取消关注", "error")
		return
	}

	c.Update(bson.M{"_id": user.Id_}, bson.M{"$pull": bson.M{"fans": currUser.Username}})
	c.Update(bson.M{"_id": currUser.Id_}, bson.M{"$pull": bson.M{"follow": user.Username}})

	http.Redirect(w, r, "/member/"+user.Username, http.StatusFound)
}
Exemple #11
0
func ArticlePageHandler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	user := auth.CurrentUser(c)

	vars := mux.Vars(r)
	page, err := strconv.ParseInt(vars["page"], 10, 32)
	if err != nil {
		page = 1
	}

	q := NewArticleQuery().Order("-CreatedOn")
	if !user.IsAdmin {
		q = q.Filter("IsPublic=", true)
	}

	p := NewArticlePager(c, q, int(page))
	articles, err := GetArticles(c, p)
	if err != nil {
		core.HandleError(c, w, err)
		return
	}

	context := tmplt.Context{
		"articles": articles,
		"pager":    p,
	}
	core.RenderTemplate(c, w, context,
		"templates/blog/articleList.html", "templates/pager.html", LAYOUT)
}
Exemple #12
0
func jsonpSendHandler(r *Router, w http.ResponseWriter, req *http.Request) {
	if xhrProlog(w, req) {
		return
	}
	w.Header().Set("Content-type", "text/plain; charset=UTF-8")
	sessionId := mux.Vars(req)["sessionid"]
	// Find the session
	s := r.getSession(sessionId)
	if s == nil {
		http.NotFoundHandler().ServeHTTP(w, req)
		return
	}
	xhrJsessionid(r, w, req)

	payload, err := extractSendContent(req)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if len(payload) == 0 {
		http.Error(w, EmptyPayload.Error(), http.StatusInternalServerError)
		return
	}
	err = s.fromClient(message(payload))
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	io.WriteString(w, "ok")
}
Exemple #13
0
func DeleteScoreHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	game, exists := games[vars["name"]]
	if !exists {
		http.Error(w, "Game doesn't exist", http.StatusBadRequest)
		return
	}
	gamescores, exists := scores[game]
	if !exists {
		http.Error(w, "Game doesn't have any scores", http.StatusBadRequest)
		return
	}
	if vars["id"] == "" {
		http.Error(w, "No score id specified", http.StatusBadRequest)
		return
	}
	id, err := strconv.Atoi(vars["id"])
	if err != nil {
		http.Error(w, "Score id should be a number", http.StatusBadRequest)
		return
	}
	_, exists = gamescores[id]
	if !exists {
		http.Error(w, "Game doesn't have score with that id", http.StatusBadRequest)
		return
	}
	delete(gamescores, id)
	fmt.Fprint(w, "")
}
Exemple #14
0
func (ep *JavascriptEndpoint) Process(response http.ResponseWriter, req *http.Request) (err error) {

	script := path.Join(ep.ScriptPath, mux.Vars(req)["javascript"])

	var file *os.File

	if file, err = os.Open(script); err != nil {
		return respond.NewNotFoundError("cannot open javascript file: %s, %s", script, err)
	}
	defer file.Close()

	var fileInfo os.FileInfo

	if fileInfo, err = file.Stat(); err != nil {
		return fmt.Errorf("can't stat javascript file: %s, %s", script, err)
	} else if fileInfo.IsDir() {
		return respond.NewNotFoundError("cannot open javascript: %s is a directory", script)
	}

	var bytes []byte

	if bytes, err = ioutil.ReadAll(file); err != nil {
		return fmt.Errorf("can't read javascript file: %s, %s", script, err)
	}

	response.Header().Add("Content-Type", "application/javascript")
	response.Write(bytes)

	return nil
}
func GetHandler(rw http.ResponseWriter, r *http.Request) {
	id_str := mux.Vars(r)["id"]
	id, err := strconv.ParseInt(id_str, 0, 0)
	if err != nil {
		rw.WriteHeader(http.StatusBadRequest)
		return
	}

	var s Session
	var found bool

	storage.RLock()
	s, found = storage.data[int(id)]
	storage.RUnlock()

	if !found {
		rw.WriteHeader(http.StatusNotFound)
		return
	}

	rw.Header().Set("content-type", "application/json")
	rw.WriteHeader(http.StatusCreated)
	enc := json.NewEncoder(rw)
	enc.Encode(&s)
}
Exemple #16
0
func PageHandler(resp http.ResponseWriter, req *http.Request) {
	vars := mux.Vars(req)
	page := vars["key"]
	md, err := loadMetadata(page)
	if err != nil {
		panic(err)
	}
	content, err := loadContent(page)
	if err != nil {
		panic(err)
	}
	tmpl, err := loadTemplate()
	if err != nil {
		panic(err)
	}
	if err := tmpl.Execute(resp, struct {
		Metadata map[string]interface{}
		Content  string
	}{
		md,
		string(content),
	}); err != nil {
		panic(err)
	}
}
Exemple #17
0
func UiAddWater(db *sql.DB, w http.ResponseWriter, r *http.Request) error {
	vars := mux.Vars(r)
	userId := vars["user"]
	user, err := models.UserById(db, userId)
	if err != nil {
		return err
	}

	o := LoadOAuth(user.AccessToken, user.AccessSecret)

	date := time.Now().Format("2006-01-02")

	data := map[string]string{
		"amount": vars["size"],
		"date":   date,
		"unit":   "fl oz",
	}

	response, err := o.Post("http://api.fitbit.com/1/user/-/foods/log/water.json", data)
	if err != nil {
		return err
	}

	waterUrl := fmt.Sprintf("http://api.fitbit.com/1/user/-/foods/log/water/date/%s.json", date)

	response, err = o.Get(waterUrl, map[string]string{})
	if err != nil {
		return err
	}
	bodyBytes, _ := ioutil.ReadAll(response.Body)

	var f interface{}
	err = json.Unmarshal(bodyBytes, &f)
	if err != nil {
		return err
	}

	m := f.(map[string]interface{})
	m = m["summary"].(map[string]interface{})
	if total, ok := m["water"].(float64); ok {

		percent := int64(math.Min((total/1419.53)*100, 100))

		tmpls, _ := template.ParseGlob("./public/tpl/*.tmpl")

		tmpls.New("content").Parse(`{{template "begin"}}{{template "waterfill" .}}{{template "end"}}`)

		args := map[string]interface{}{
			"User":    user,
			"Percent": percent,
		}

		tmpls.ExecuteTemplate(w, "content", args)

		return nil
	}

	return nil
}
Exemple #18
0
func DeleteHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	if !RemoveGull(vars["id"]) {
		http.Error(w, "Invalid sighting id.", http.StatusNotFound)
		return
	}
	http.Redirect(w, r, "/", 302)
}
Exemple #19
0
func RenderJavascripts(res http.ResponseWriter, req *http.Request) {

	script := fmt.Sprintf("./webapp/js/%s", mux.Vars(req)["script"])

	res.Header().Add("Content-Type", "application/javascript")

	textTemplate.Must(textTemplate.ParseFiles(script)).Execute(res, req.Host)
}
Exemple #20
0
func (self *ControllerArtist) Show(w http.ResponseWriter, r *http.Request) {
	id, err := strconv.Atoi(mux.Vars(r)["id"])
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	if err := self.Env.Db.BeginTransaction(); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer self.Env.Db.EndTransaction()

	// retreive artist by id
	var artist artist.Artist

	err = query.New(self.Env.Db, "artist").Find(id).Exec(&artist)

	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// retreive albums of artist
	var albums []album.Album

	err = artist.AlbumsQuery(self.Env.Db).Order("name").Exec(&albums)

	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// prepare data for template
	for i := 0; i < len(albums); i++ {
		url, err := self.URL("album", controller.Pairs{"id": albums[i].Id})

		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		albums[i].Link = url
	}

	self.Tmpl.AddDataToTemplate("artist_show", "Artist", &artist)
	self.Tmpl.AddDataToTemplate("artist_show", "Albums", &albums)

	backlink, _ := self.URL("artist_base", nil)

	// render the website
	self.Tmpl.RenderPage(
		w,
		"artist_show",
		&tmpl.Page{Title: artist.Name, BackLink: backlink},
	)
}
Exemple #21
0
// url: /user/{user}
func handleUser(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	userName := vars["user"]

	//fmt.Printf("handleUser() user=%s\n", userName)
	model := buildModelUser(userName, decodeUserFromCookie(r))
	model.RedirectUrl = r.URL.String()
	ExecTemplate(w, tmplUser, model)
}
Exemple #22
0
//Search handles the web requests and writes the output as
//json data.
func Search(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	query := vars["query"]

	searchResult := CleoSearch(m.iIndex, m.fIndex, query)
	sort.Sort(ByScore{searchResult})
	myJson, _ := json.Marshal(searchResult)
	fmt.Fprintf(w, string(myJson))
}
Exemple #23
0
func AddUserHandler(w http.ResponseWriter, r *http.Request) {
	// allow cross domain AJAX requests
	w.Header().Set("Access-Control-Allow-Origin", "http://pleskac.org")
	vars := mux.Vars(r)
	useremail := vars[email]
	fmt.Println(useremail)

	dblayer.AddUser(vars[email], vars[username], vars[displayname], vars[userpassword])
}
Exemple #24
0
func ArticleUpdateHandler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	user := core.AdminUser(c, w)
	if user == nil {
		return
	}

	vars := mux.Vars(r)
	id, err := strconv.ParseInt(vars["id"], 10, 64)
	if err != nil {
		core.HandleError(c, w, err)
		return
	}

	article, err := GetArticleById(c, id, false)
	if err != nil {
		core.HandleNotFound(c, w)
		return
	}

	form := NewArticleForm(article)

	if r.Method == "POST" {
		if err := r.ParseForm(); err != nil {
			core.HandleError(c, w, err)
			return
		}

		if gforms.IsFormValid(form, r.Form) {
			err := UpdateArticle(c, article,
				form.Title.Value(),
				form.Text.Value(),
				form.IsPublic.Value(),
			)
			if err != nil {
				core.HandleError(c, w, err)
				return
			}

			redirectTo, err := article.URL()
			if err != nil {
				core.HandleError(c, w, err)
				return
			}
			http.Redirect(w, r, redirectTo.Path, 302)
		}
	}

	context := map[string]interface{}{
		"article": article,
		"form":    form,
	}
	core.RenderTemplate(c, w, context,
		"templates/blog/articleUpdate.html", "templates/blog/articleForm.html", LAYOUT)
}
Exemple #25
0
func apiDeleteSingleHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	_, ok := blocklist[vars["uuid"]]
	if conditionalFailf(w, !ok, http.StatusNotFound, "DeleteSingle: Unknown UUID %s", vars["uuid"]) {
		return
	}

	delete(blocklist, vars["uuid"])
	w.WriteHeader(http.StatusNoContent)
}
Exemple #26
0
func ViewHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	gull, exists := gulls[vars["id"]]
	if !exists {
		http.Error(w, "Invalid sighting id.", http.StatusNotFound)
		return
	}
	enc := json.NewEncoder(w)
	enc.Encode(gull)
}
Exemple #27
0
func getFormat(r *http.Request) string {
	// should also allow Content-Accept
	vars := mux.Vars(r)
	if vars["format"] == "" || vars["format"] == ".html" {
		return "html"
	} else if vars["format"] == ".json" {
		return "json"
	}
	return "html"
}
Exemple #28
0
func staticHandler(w http.ResponseWriter, r *http.Request) {
	filename := mux.Vars(r)["filename"]
	w.Header().Set("Cache-Control", "no-cache")
	filepath := path.Join(StaticDir, filename)
	if stat, err := os.Stat(filepath); err != nil || stat.IsDir() {
		http.NotFound(w, r)
		return
	}
	http.ServeFile(w, r, filepath)
}
Exemple #29
0
func DeleteGameHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	_, exists := games[vars["name"]]
	if !exists {
		http.Error(w, "Game doesn't exist", http.StatusBadRequest)
		return
	}
	delete(games, vars["name"])
	fmt.Fprint(w, "")
}
Exemple #30
0
func ShowGameHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	game, exists := games[vars["name"]]
	if !exists {
		http.Error(w, "Game doesn't exist", http.StatusBadRequest)
		return
	}
	response, _ := json.Marshal(game)
	fmt.Fprint(w, string(response))
}