Golang ResponseWriter.Write Examples

Golang ResponseWriter.Write - 30 examples found. These are the top rated real world Golang examples of net/http.ResponseWriter.Write extracted from open source projects. You can rate examples to help us improve the quality of examples.
Example #1
0
// 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)
}
Example #2
0
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
}
Example #3
0
// 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
}
Example #4
0
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)
}
Example #5
0
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"))
	}
}
Example #6
0
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()))
	}

}