当前位置: 首页>>代码示例>>Golang>>正文


Golang http.ResponseWriter类代码示例

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


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

示例1: TodoIndex

func TodoIndex(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusOK)
	if err := json.NewEncoder(w).Encode(todos); err != nil {
		panic(err)
	}
}
开发者ID:banlong,项目名称:cut2it-mediaResful,代码行数:7,代码来源:handlers.go

示例2: WriteSuccess

func WriteSuccess(w http.ResponseWriter, code int) error {
	fmt.Println(code)
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.WriteHeader(code)
	item := Item{Item: "success"}
	return json.NewEncoder(w).Encode(item)
}
开发者ID:cclient,项目名称:gowebframework,代码行数:7,代码来源:httputils.go

示例3: ServeHTTP

// ServeHTTP dispatches the handler registered in the matched route.
//
// When there is a match, the route variables can be retrieved calling
// mux.Vars(request).
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	// Clean path to canonical form and redirect.
	if p := cleanPath(req.URL.Path); p != req.URL.Path {

		// Added 3 lines (Philip Schlump) - It was dropping the query string and #whatever from query.
		// This matches with fix in go 1.2 r.c. 4 for same problem.  Go Issue:
		// http://code.google.com/p/go/issues/detail?id=5252
		url := *req.URL
		url.Path = p
		p = url.String()

		w.Header().Set("Location", p)
		w.WriteHeader(http.StatusMovedPermanently)
		return
	}
	var match RouteMatch
	var handler http.Handler
	if r.Match(req, &match) {
		handler = match.Handler
		setVars(req, match.Vars)
		setCurrentRoute(req, match.Route)
	}
	if handler == nil {
		handler = r.NotFoundHandler
		if handler == nil {
			handler = http.NotFoundHandler()
		}
	}
	if !r.KeepContext {
		defer context.Clear(req)
	}
	handler.ServeHTTP(w, req)
}
开发者ID:nofdev,项目名称:fastforward,代码行数:37,代码来源:mux.go

示例4: raw_balance

func raw_balance(w http.ResponseWriter, r *http.Request) {
	if !ipchecker(r) {
		return
	}

	w.Write([]byte(wallet.UpdateBalanceFolder()))
}
开发者ID:vipwzw,项目名称:gocoin,代码行数:7,代码来源:wallets.go

示例5: postContainersKill

func postContainersKill(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
	if vars == nil {
		return fmt.Errorf("Missing parameter")
	}
	if err := parseForm(r); err != nil {
		return err
	}
	name := vars["name"]

	signal := 0
	if r != nil {
		s := r.Form.Get("signal")
		if s != "" {
			if s, err := strconv.Atoi(s); err != nil {
				return err
			} else {
				signal = s
			}
		}
	}
	if err := srv.ContainerKill(name, signal); err != nil {
		return err
	}
	w.WriteHeader(http.StatusNoContent)
	return nil
}
开发者ID:juniorz,项目名称:docker,代码行数:26,代码来源:api.go

示例6: showBlockPage

// showBlockPage shows a block page for a page that was blocked by an ACL.
func (c *config) showBlockPage(w http.ResponseWriter, r *http.Request, resp *http.Response, user string, tally map[rule]int, scores map[string]int, rule ACLActionRule) {
	w.WriteHeader(http.StatusForbidden)
	if c.BlockTemplate == nil {
		return
	}
	data := blockData{
		URL:        r.URL.String(),
		Conditions: rule.Conditions(),
		User:       user,
		Tally:      listTally(stringTally(tally)),
		Scores:     listTally(scores),
		Request:    r,
		Response:   resp,
	}
	w.Header().Set("Content-Type", "text/html; charset=utf-8")

	// Convert rule conditions into category descriptions as much as possible.
	var categories []string
	for _, acl := range rule.Needed {
		categories = append(categories, c.aclDescription(acl))
	}
	for _, acl := range rule.Disallowed {
		categories = append(categories, "not "+c.aclDescription(acl))
	}
	data.Categories = strings.Join(categories, ", ")

	err := c.BlockTemplate.Execute(w, data)
	if err != nil {
		log.Println("Error filling in block page template:", err)
	}
}
开发者ID:soccerties,项目名称:redwood,代码行数:32,代码来源:blockpage.go

示例7: randHandler

func randHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Println("rand:")
	if true {
		w.Header().Set("ContentType", "text/html")
		io.WriteString(w, strconv.FormatFloat(rand.Float64(), 'g', 10, 64))
	}
}
开发者ID:taysom,项目名称:va,代码行数:7,代码来源:plot.go

示例8: createPost

func createPost(c *Context, w http.ResponseWriter, r *http.Request) {
	post := model.PostFromJson(r.Body)
	if post == nil {
		c.SetInvalidParam("createPost", "post")
		return
	}

	// Create and save post object to channel
	cchan := Srv.Store.Channel().CheckPermissionsTo(c.TeamId, post.ChannelId, c.Session.UserId)

	if !c.HasPermissionsToChannel(cchan, "createPost") {
		return
	}

	if rp, err := CreatePost(c, post, true); err != nil {
		c.Err = err

		if c.Err.Id == "api.post.create_post.root_id.app_error" ||
			c.Err.Id == "api.post.create_post.channel_root_id.app_error" ||
			c.Err.Id == "api.post.create_post.parent_id.app_error" {
			c.Err.StatusCode = http.StatusBadRequest
		}

		return
	} else {
		if result := <-Srv.Store.Channel().UpdateLastViewedAt(post.ChannelId, c.Session.UserId); result.Err != nil {
			l4g.Error(utils.T("api.post.create_post.last_viewed.error"), post.ChannelId, c.Session.UserId, result.Err)
		}

		w.Write([]byte(rp.ToJson()))
	}
}
开发者ID:carriercomm,项目名称:platform,代码行数:32,代码来源:post.go

示例9: getPostsSince

func getPostsSince(c *Context, w http.ResponseWriter, r *http.Request) {
	params := mux.Vars(r)

	id := params["channel_id"]
	if len(id) != 26 {
		c.SetInvalidParam("getPostsSince", "channelId")
		return
	}

	time, err := strconv.ParseInt(params["time"], 10, 64)
	if err != nil {
		c.SetInvalidParam("getPostsSince", "time")
		return
	}

	cchan := Srv.Store.Channel().CheckPermissionsTo(c.TeamId, id, c.Session.UserId)
	pchan := Srv.Store.Post().GetPostsSince(id, time)

	if !c.HasPermissionsToChannel(cchan, "getPostsSince") {
		return
	}

	if result := <-pchan; result.Err != nil {
		c.Err = result.Err
		return
	} else {
		list := result.Data.(*model.PostList)

		w.Write([]byte(list.ToJson()))
	}

}
开发者ID:carriercomm,项目名称:platform,代码行数:32,代码来源:post.go

示例10: Register

func Register(w http.ResponseWriter, r *http.Request) {

	user := models.User{}

	if r.FormValue("displayName") != "" {
		user.DisplayName = r.FormValue("displayName")
	} else {
		user.DisplayName = "NULL"
	}

	_email := r.FormValue("email")
	if _email != "" {
		user.Email.Scan(_email)
	}

	if r.FormValue("password") != "" {
		user.Password = r.FormValue("password")
	} else {
		user.Password = "NULL"
	}

	createUserToken(&user)

	if err := repository.CreateUser(&user).Error; err != nil {
		w.WriteHeader(http.StatusForbidden)
		json.NewEncoder(w).Encode(err)
		return
	}

	log.Println(user)

	json.NewEncoder(w).Encode(user)
}
开发者ID:khaiql,项目名称:instagram-go,代码行数:33,代码来源:user.go

示例11: getPostById

func getPostById(c *Context, w http.ResponseWriter, r *http.Request) {
	params := mux.Vars(r)

	postId := params["post_id"]
	if len(postId) != 26 {
		c.SetInvalidParam("getPostById", "postId")
		return
	}

	if result := <-Srv.Store.Post().Get(postId); result.Err != nil {
		c.Err = result.Err
		return
	} else {
		list := result.Data.(*model.PostList)

		if len(list.Order) != 1 {
			c.Err = model.NewLocAppError("getPostById", "api.post_get_post_by_id.get.app_error", nil, "")
			return
		}
		post := list.Posts[list.Order[0]]

		cchan := Srv.Store.Channel().CheckPermissionsTo(c.TeamId, post.ChannelId, c.Session.UserId)
		if !c.HasPermissionsToChannel(cchan, "getPostById") {
			return
		}

		if HandleEtag(list.Etag(), w, r) {
			return
		}

		w.Header().Set(model.HEADER_ETAG_SERVER, list.Etag())
		w.Write([]byte(list.ToJson()))
	}
}
开发者ID:carriercomm,项目名称:platform,代码行数:34,代码来源:post.go

示例12: ServeHTTP

func (h *SitemapHandler) ServeHTTP(out http.ResponseWriter, req *http.Request) {
	out.Header().Set("Content-Type", "text/plain; charset=utf-8")
	h.store.IterateAll(func(c *Component) bool {
		fmt.Fprintf(out, "%s/form?id=%d\n", h.siteprefix, c.Id)
		return true
	})
}
开发者ID:hzeller,项目名称:stuff-org,代码行数:7,代码来源:sitemap-handler.go

示例13: error

func (srv *Server) error(w http.ResponseWriter, err *iam.Error) {
	w.WriteHeader(err.StatusCode)
	xmlErr := xmlErrors{Error: *err}
	if e := xml.NewEncoder(w).Encode(xmlErr); e != nil {
		panic(e)
	}
}
开发者ID:fsouza,项目名称:go-iam,代码行数:7,代码来源:server.go

示例14: pubHandler

func pubHandler(w http.ResponseWriter, req *http.Request) {
	name := req.FormValue("topic")
	if name == "" {
		http.Error(w, "missing topic", 403)
		return
	}
	size, err := strconv.Atoi(req.FormValue("size"))
	if err != nil {
		http.Error(w, err.Error(), 403)
		return
	}

	var (
		msg    *message.Ins
		header message.Header
		msgs   = make([]*message.Ins, 0, size)
	)
	for !logex.Equal(err, io.EOF) {
		msg, err = message.ReadMessage(&header, req.Body, message.RF_DEFAULT)
		if err != nil {
			break
		}
		msgs = append(msgs, msg)
	}

	t, err := getTopic(name)
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}
	t.PutSync(msgs)
	w.Write([]byte("hello"))
}
开发者ID:chzyer-dev,项目名称:muxque,代码行数:33,代码来源:server.go

示例15: getJSMetadata

func (s *apiService) getJSMetadata(w http.ResponseWriter, r *http.Request) {
	meta, _ := json.Marshal(map[string]string{
		"deviceID": s.id.String(),
	})
	w.Header().Set("Content-Type", "application/javascript")
	fmt.Fprintf(w, "var metadata = %s;\n", meta)
}
开发者ID:xduugu,项目名称:syncthing,代码行数:7,代码来源:gui.go


注:本文中的net/http.ResponseWriter类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。