• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang mux.Vars函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中code/google/com/p/gorilla/mux.Vars函数的典型用法代码示例。如果您正苦于以下问题:Golang Vars函数的具体用法?Golang Vars怎么用?Golang Vars使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了Vars函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: ArticlePermaLinkHandler

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)
}
开发者ID:vmihailenco,项目名称:goblog,代码行数:31,代码来源:handlers.go


示例2: ShowScoreHandler

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))
}
开发者ID:errnoh,项目名称:wepa2012,代码行数:29,代码来源:controller.go


示例3: shorten

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)
}
开发者ID:olivere,项目名称:shroty,代码行数:7,代码来源:shroty.go


示例4: xhrSendHandler

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)
}
开发者ID:mrlauer,项目名称:gosockjs,代码行数:28,代码来源:xhr.go


示例5: coffeeHandler

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()))
}
开发者ID:mrlauer,项目名称:sniffer,代码行数:33,代码来源:websniffer.go


示例6: ArticleDeleteHandler

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)
}
开发者ID:vmihailenco,项目名称:goblog,代码行数:29,代码来源:handlers.go


示例7: AddGPSHandler

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, "[email protected]")

	enc := json.NewEncoder(w)
	enc.Encode(standardType)
}
开发者ID:pleskac,项目名称:SpotLocator,代码行数:33,代码来源:endpoint.go


示例8: XhrSendHandler

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)
	}
}
开发者ID:prinsmike,项目名称:sockjs-go,代码行数:33,代码来源:xhr-send.go


示例9: followHandler

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)
}
开发者ID:hongruiqi,项目名称:gopher,代码行数:31,代码来源:account.go


示例10: unfollowHandler

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)
}
开发者ID:hongruiqi,项目名称:gopher,代码行数:31,代码来源:account.go


示例11: ArticlePageHandler

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)
}
开发者ID:vmihailenco,项目名称:goblog,代码行数:29,代码来源:handlers.go


示例12: jsonpSendHandler

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")
}
开发者ID:mrlauer,项目名称:gosockjs,代码行数:30,代码来源:jsonp.go


示例13: DeleteScoreHandler

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, "")
}
开发者ID:errnoh,项目名称:wepa2012,代码行数:29,代码来源:controller.go


示例14: Process

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
}
开发者ID:sjltaylor,项目名称:respond,代码行数:30,代码来源:javascripts.go


示例15: GetHandler

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)
}
开发者ID:michaljemala,项目名称:backbonejs-sample,代码行数:25,代码来源:main.go


示例16: PageHandler

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)
	}
}
开发者ID:davecheney,项目名称:zuul,代码行数:25,代码来源:main.go


示例17: UiAddWater

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
}
开发者ID:DDRBoxman,项目名称:Water-Cooler,代码行数:59,代码来源:ui_water.go


示例18: DeleteHandler

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)
}
开发者ID:errnoh,项目名称:wepa2012,代码行数:8,代码来源:controllers.go


示例19: RenderJavascripts

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)
}
开发者ID:sjltaylor,项目名称:datagram.io,代码行数:8,代码来源:render.go


示例20: Show

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},
	)
}
开发者ID:yeison,项目名称:musicrawler,代码行数:57,代码来源:artist.go



注:本文中的code/google/com/p/gorilla/mux.Vars函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang sessions.NewCookieStore函数代码示例发布时间:2022-05-24
下一篇:
Golang mux.NewRouter函数代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap