Пример #1
0
func (s *Server) HandlePostLog(w http.ResponseWriter, r *http.Request) {
	if !strings.HasPrefix(r.Header.Get("Content-Type"), "application/json") {
		http.Error(w, "JSON requests only", http.StatusNotAcceptable)
		return
	}

	ctx := NewContext(r, w)
	user := ctx.User()
	if user == nil {
		http.Error(w, "unauthorized", http.StatusUnauthorized)
		return
	}

	var req postLogRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	name := strings.TrimSuffix(req.Filename, ".gpx")
	log, err := models.NewLog(name, []byte(req.GPX))
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	if err := s.db.AddUserLog(user, log); err != nil {
		panic(err)
	}

	w.WriteHeader(http.StatusCreated)
	resp := postLogResponse{ID: log.ID}
	json.NewEncoder(w).Encode(resp)
}
Пример #2
0
func importFile(user *models.User, fileName string) error {
	f, err := os.Open(fileName)
	if err != nil {
		return err
	}
	defer f.Close()

	data, err := ioutil.ReadAll(f)
	if err != nil {
		return err
	}

	name := strings.TrimSuffix(path.Base(fileName), ".gpx")
	log, err := models.NewLog(name, data)
	if err != nil {
		return err
	}

	return database.AddUserLog(user, log)
}