本文整理汇总了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)
}
}
示例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)
}
示例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)
}
示例4: raw_balance
func raw_balance(w http.ResponseWriter, r *http.Request) {
if !ipchecker(r) {
return
}
w.Write([]byte(wallet.UpdateBalanceFolder()))
}
示例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
}
示例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)
}
}
示例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))
}
}
示例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()))
}
}
示例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()))
}
}
示例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)
}
示例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()))
}
}
示例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
})
}
示例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)
}
}
示例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"))
}
示例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)
}