Пример #1
0
// :WEBAPI:
// {
//   "url": "{schema}://{host}/api/v1/tasks",
//   "method": "POST",
//   "description": "Creates new task"
// }
func TaskCreateHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	cfg, ok := ctx.Value("app.config").(*config.Config)
	if !ok {
		ahttp.HTTPResponse(w, http.StatusInternalServerError, "Unable to obtain config from context")
		return
	}

	msg, err := ioutil.ReadAll(r.Body)
	if err != nil {
		ahttp.HTTPResponse(w, http.StatusBadRequest, "Unable to read body: %s", err)
		return
	}
	logger.GetHTTPEntry(ctx).WithFields(nil).Infof("TaskCreateHandler: Request body: %s", string(msg))

	ev := task.NewTaskEvent()
	if err = json.Unmarshal(msg, ev); err != nil {
		ahttp.HTTPResponse(w, http.StatusBadRequest, "Invalid JSON: %s", err)
		return
	}

	t := task.New()
	fillTask(t, ev)

	t.TimeCreate.Set(time.Now().Unix())

	logger.GetHTTPEntry(ctx).WithFields(nil).Infof("TaskCreateHandler: Task: %+v", t)

	if v, ok := t.Repo.Get(); ok {
		if !util.InSliceString(v, cfg.Builder.Repos) {
			ahttp.HTTPResponse(w, http.StatusBadRequest, "Unknown repo")
			return
		}
	} else {
		ahttp.HTTPResponse(w, http.StatusBadRequest, "repo: mandatory field is not specified")
		return
	}

	if !t.Owner.IsDefined() {
		ahttp.HTTPResponse(w, http.StatusBadRequest, "owner: mandatory field is not specified")
		return
	}

	if !writeTask(ctx, w, t) {
		return
	}

	ahttp.HTTPResponse(w, http.StatusOK, "OK")
}
Пример #2
0
func writeTask(ctx context.Context, w http.ResponseWriter, t *task.Task) bool {
	st, ok := ctx.Value("app.database").(db.Session)
	if !ok {
		ahttp.HTTPResponse(w, http.StatusInternalServerError, "Unable to obtain database from context")
		return false
	}

	cfg, ok := ctx.Value("app.config").(*config.Config)
	if !ok {
		ahttp.HTTPResponse(w, http.StatusInternalServerError, "Unable to obtain config from context")
		return false
	}

	if v, ok := t.TaskID.Get(); ok {
		if v < int64(1) {
			ahttp.HTTPResponse(w, http.StatusBadRequest, "taskid must be greater than zero")
			return false
		}
	} else {
		ahttp.HTTPResponse(w, http.StatusBadRequest, "taskid: mandatory field is not specified")
		return false
	}

	if v, ok := t.State.Get(); ok {
		if !util.InSliceString(v, cfg.Builder.TaskStates) {
			ahttp.HTTPResponse(w, http.StatusBadRequest, "Unknown state")
			return false
		}
	}

	if err := task.Write(st, t); err != nil {
		if db.IsDup(err) {
			ahttp.HTTPResponse(w, http.StatusBadRequest, "Already exists")
		} else {
			ahttp.HTTPResponse(w, http.StatusInternalServerError, "%+v", err)
		}
		return false
	}

	return true
}