本文整理汇总了Golang中net/http.ResponseWriter.Write方法的典型用法代码示例。如果您正苦于以下问题:Golang ResponseWriter.Write方法的具体用法?Golang ResponseWriter.Write怎么用?Golang ResponseWriter.Write使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net/http.ResponseWriter
的用法示例。
在下文中一共展示了ResponseWriter.Write方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: register
// Create a new user and store that user. Once successfully concluded a JWT
// access token will be returned to the user
func register(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
type payload struct {
Email string
Password string
}
pl := payload{}
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&pl)
if err != nil {
http.Error(w, "Could not read the given request body", http.StatusBadRequest)
return
}
user, goAuthErr := userService.Register(pl.Email, pl.Password)
if goAuthErr != nil {
http.Error(w, goAuthErr.Message, goAuthErr.Status)
return
}
response, err := authResponse(user)
if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(response)
}
示例2: raw_balance
func raw_balance(w http.ResponseWriter, r *http.Request) {
if !ipchecker(r) {
return
}
w.Write([]byte(wallet.UpdateBalanceFolder()))
}
示例3: SessionRenew
// SessionRenew is used to renew the TTL on an existing TTL session
func (s *HTTPServer) SessionRenew(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
// Mandate a PUT request
if req.Method != "PUT" {
resp.WriteHeader(405)
return nil, nil
}
args := structs.SessionSpecificRequest{}
if done := s.parse(resp, req, &args.Datacenter, &args.QueryOptions); done {
return nil, nil
}
// Pull out the session id
args.Session = strings.TrimPrefix(req.URL.Path, "/v1/session/renew/")
if args.Session == "" {
resp.WriteHeader(400)
resp.Write([]byte("Missing session"))
return nil, nil
}
var out structs.IndexedSessions
if err := s.agent.RPC("Session.Renew", &args, &out); err != nil {
return nil, err
} else if out.Sessions == nil {
resp.WriteHeader(404)
resp.Write([]byte(fmt.Sprintf("Session id '%s' not found", args.Session)))
return nil, nil
}
return out.Sessions, nil
}
示例4: postImagesInsert
func postImagesInsert(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
url := r.Form.Get("url")
path := r.Form.Get("path")
if vars == nil {
return fmt.Errorf("Missing parameter")
}
name := vars["name"]
if version > 1.0 {
w.Header().Set("Content-Type", "application/json")
}
sf := utils.NewStreamFormatter(version > 1.0)
err := srv.ImageInsert(name, url, path, w, sf)
if err != nil {
if sf.Used() {
w.Write(sf.FormatError(err))
return nil
}
return err
}
return nil
}
示例5: dl_balance
func dl_balance(w http.ResponseWriter, r *http.Request) {
if !ipchecker(r) {
return
}
wallet.UpdateBalanceFolder()
buf := new(bytes.Buffer)
zi := zip.NewWriter(buf)
filepath.Walk("balance/", func(path string, fi os.FileInfo, err error) error {
if !fi.IsDir() {
f, _ := zi.Create(path)
if f != nil {
da, _ := ioutil.ReadFile(path)
f.Write(da)
}
}
return nil
})
if zi.Close() == nil {
w.Header()["Content-Type"] = []string{"application/zip"}
w.Write(buf.Bytes())
} else {
w.Write([]byte("Error"))
}
}
示例6: Set
func (t *TasksHandler) Set(w http.ResponseWriter, r *http.Request) {
blob, err := ioutil.ReadAll(r.Body)
if err != nil {
HandleError(err, w)
return
}
defer r.Body.Close()
task := new(state.Task)
err = json.Unmarshal(blob, task)
if err != nil {
HandleError(err, w)
return
}
// validate
if id, ok := mux.Vars(r)["id"]; ok && id != task.ID {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("body ID does not match URL ID"))
return
}
err = t.store.Update(task)
if err != nil {
HandleError(err, w)
return
}
headers := w.Header()
headers.Add("Location", "/1/tasks/"+task.ID)
w.WriteHeader(http.StatusCreated)
}
示例7: ServeHTTP
func (h *UploadHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
oa := CheckAuthorized(w, r, false)
if oa == nil {
return
}
if r.Method != "POST" {
http.Redirect(w, r, "/", http.StatusFound)
return
}
m, _, err := r.FormFile("server")
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
defer m.Close()
dst, err := os.Create(deployFileName)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
_, err = io.Copy(dst, m)
dst.Close()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
finfo, _ := os.Stat(deployFileName)
w.WriteHeader(200)
w.Write([]byte("Uploaded: " + humanize.Bytes(uint64(finfo.Size()))))
}
示例8: 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()))
}
}
示例9: CentralGetRoot
func CentralGetRoot(w http.ResponseWriter, r *http.Request) {
readOnly := context.Get(r, "readOnly").(bool)
if readOnly {
w.Write([]byte(`{
paths: {
GET: [
"/configs",
"/configs/:hostname",
"/stats",
"/stats/:hostname"
]
}
}`))
} else {
w.Write([]byte(`{
paths: {
GET: [
"/configs",
"/configs/:hostname",
"/stats",
"/stats/:hostname"
],
POST: [
"/configs",
"/stats"
]
}
}`))
}
}
示例10: OperatorRaftPeer
// OperatorRaftPeer supports actions on Raft peers. Currently we only support
// removing peers by address.
func (s *HTTPServer) OperatorRaftPeer(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
if req.Method != "DELETE" {
resp.WriteHeader(http.StatusMethodNotAllowed)
return nil, nil
}
var args structs.RaftPeerByAddressRequest
s.parseDC(req, &args.Datacenter)
s.parseToken(req, &args.Token)
params := req.URL.Query()
if _, ok := params["address"]; ok {
args.Address = raft.ServerAddress(params.Get("address"))
} else {
resp.WriteHeader(http.StatusBadRequest)
resp.Write([]byte("Must specify ?address with IP:port of peer to remove"))
return nil, nil
}
var reply struct{}
if err := s.agent.RPC("Operator.RaftRemovePeerByAddress", &args, &reply); err != nil {
return nil, err
}
return nil, nil
}
示例11: Get
func (i *Incident) Get(w http.ResponseWriter, r *http.Request) {
w.Header().Add("content-type", "application/json")
vars := mux.Vars(r)
id, ok := vars["id"]
if !ok {
http.Error(w, "Must append incident id", http.StatusBadRequest)
return
}
index := i.pipeline.GetIndex()
// if the id is "*", fetch all outstanding incidents
if id == "*" {
all := index.ListIncidents()
all = reduceStatusAbove(event.WARNING, all)
buff, err := json.Marshal(makeKV(all))
if err != nil {
logrus.Error(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(buff)
return
}
// write out the found incident. The value will be null if nothing was found
in := index.GetIncident([]byte(id))
buff, err := json.Marshal(in)
if err != nil {
logrus.Error(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(buff)
}
示例12: servePriorityInfo
func (sq *SubmitQueue) servePriorityInfo(res http.ResponseWriter, req *http.Request) {
res.Header().Set("Content-type", "text/plain")
res.WriteHeader(http.StatusOK)
res.Write([]byte(`The merge queue is sorted by the following. If there is a tie in any test the next test will be used. A P0 will always come before a P1, no matter how the other tests compare.
<ol>
<li>Priority
<ul>
<li>Determined by a label of the form 'priority/pX'
<li>P0 -> P1 -> P2</li>
<li>A PR with no priority label is considered equal to a P3</li>
<li>A PR with the '` + retestNotRequiredLabel + `' or '` + retestNotRequiredDocsOnlyLabel + `' label will come first, before even P0</li>
</ul>
</li>
<li>Release milestone due date
<ul>
<li>Release milestones are of the form vX.Y where X and Y are integers</li>
<li>Other milestones are ignored.
<li>PR with no release milestone will be considered after any PR with a milestone</li>
</ul>
</li>
<li>First time at which the LGTM label was applied.
<ul>
<li>This means all PRs start at the bottom of the queue (within their priority and milestone bands, of course) and progress towards the top.</li>
</ul>
</li>
</ol> `))
}
示例13: ServeHTTP
// Base handler for HTTP requests.
func (*handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
if strings.HasPrefix(path, "/css/") {
path = strings.TrimLeft(path, "/css/")
if css, ok := assets.Css[path]; ok {
w.Header().Set("Content-Type", "text/css; charset=utf-8")
w.Write([]byte(css))
} else {
w.WriteHeader(http.StatusNotFound)
}
} else if path == "/favicon.ico" {
} else {
var file []byte
path = strings.TrimLeft(path, "/")
if path == "" {
file = markdown.GetReadme()
} else {
file = markdown.GetFile(path)
}
data := data{
Title: "Knowledge Base",
Index: template.HTML(string(markdown.GetIndex())),
Content: template.HTML(string(file)),
}
render(w, data)
}
}
示例14: postRegister
func postRegister(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
username, password := r.PostFormValue("username"), r.PostFormValue("password")
if !recaptcher.Verify(*r) {
logger.WithFields(logrus.Fields{
"user": username,
"error": recaptcher.LastError(),
}).Error("Failed to verify reCaptcha during registration.")
w.Write([]byte("Failed to verify the reCaptcha. Please verify that you are human and try again."))
return
}
err := users.Register(username, password)
switch err {
case nil:
//Success
logger.WithFields(logrus.Fields{
"method": r.Method,
"url": r.URL,
"client": r.RemoteAddr,
"user": username,
}).Info("User registration")
renderer.Render(w, pages.Get(RegistrationSuccessPage))
case ErrUserExists:
http.Error(w, "The user already exists. Please try again with a different username.", http.StatusPreconditionFailed)
default:
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
示例15: teamList
func teamList(w http.ResponseWriter, r *http.Request, t *auth.Token) error {
u, err := t.User()
if err != nil {
return err
}
rec.Log(u.Email, "list-teams")
teams, err := u.Teams()
if err != nil {
return err
}
if len(teams) > 0 {
var result []map[string]string
for _, team := range teams {
result = append(result, map[string]string{"name": team.Name})
}
b, err := json.Marshal(result)
if err != nil {
return err
}
n, err := w.Write(b)
if err != nil {
return err
}
if n != len(b) {
return &errors.HTTP{Code: http.StatusInternalServerError, Message: "Failed to write response body."}
}
} else {
w.WriteHeader(http.StatusNoContent)
}
return nil
}