当前位置: 首页>>代码示例>>Golang>>正文


Golang context.Context类代码示例

本文整理汇总了Golang中github.com/altlinux/webery/pkg/context.Context的典型用法代码示例。如果您正苦于以下问题:Golang Context类的具体用法?Golang Context怎么用?Golang Context使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Context类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: SubtaskDeleteHandler

// :WEBAPI:
// {
//   "url": "{schema}://{host}/api/v1/tasks/{taskid}/subtasks/{subtaskid}",
//   "method": "DELETE",
//   "arguments": [
//     {"name": "taskid",    "type": "integer", "description": "task number"},
//     {"name": "subtaskid", "type": "integer", "description": "subtask number"}
//   ],
//   "description": "Removes subtask"
// }
func SubtaskDeleteHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	p, ok := ctx.Value("http.request.query.params").(*url.Values)
	if !ok {
		ahttp.HTTPResponse(w, http.StatusInternalServerError, "Unable to obtain params from context")
		return
	}

	st, ok := ctx.Value("app.database").(db.Session)
	if !ok {
		ahttp.HTTPResponse(w, http.StatusInternalServerError, "Unable to obtain database from context")
		return
	}

	subtaskID := subtask.MakeID(util.ToInt64(p.Get("task")), util.ToInt64(p.Get("subtask")))

	if err := subtask.Delete(st, subtaskID); err != nil {
		if db.IsNotFound(err) {
			ahttp.HTTPResponse(w, http.StatusNotFound, "Not found")
		} else {
			ahttp.HTTPResponse(w, http.StatusInternalServerError, "Unable to delete: %v", err)
		}
		return
	}

	ahttp.HTTPResponse(w, http.StatusOK, "OK")
}
开发者ID:altlinux,项目名称:webery,代码行数:36,代码来源:subtasks.go

示例2: SearchHandler

// :WEBAPI:
// {
//   "url": "{schema}://{host}/api/v1/search",
//   "method": "GET",
//   "parameters": [
//     {"name": "prefix", "type": "string", "description": "filter objects by prefix", "default": "NaN"},
//     {"name": "limit",  "type": "number", "description": "shows only specified number of retults", "default": "1000"}
//   ],
//   "description": "Returns list of tasks and subtasks"
// }
func SearchHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	p, ok := ctx.Value("http.request.query.params").(*url.Values)
	if !ok {
		ahttp.HTTPResponse(w, http.StatusInternalServerError, "Unable to obtain params from context")
		return
	}

	apiSearch(ctx, w, r, []Query{
		Query{
			CollName: task.CollName,
			Pattern:  db.QueryDoc{"search.key": db.QueryDoc{"$regex": "^" + p.Get("prefix")}},
			Sort:     []string{"-taskid"},
			Iterator: func(iter db.Iter) interface{} {
				t := task.New()
				if !iter.Next(t) {
					return nil
				}
				return t
			},
		},
		Query{
			CollName: subtask.CollName,
			Pattern:  db.QueryDoc{"search.key": db.QueryDoc{"$regex": "^" + p.Get("prefix")}},
			Sort:     []string{"-taskid"},
			Iterator: func(iter db.Iter) interface{} {
				t := subtask.New()
				if !iter.Next(t) {
					return nil
				}
				return t
			},
		},
	})
}
开发者ID:altlinux,项目名称:webery,代码行数:44,代码来源:search.go

示例3: apiGet

func apiGet(ctx context.Context, w http.ResponseWriter, r *http.Request, query Query) {
	st, ok := ctx.Value("app.database").(db.Session)
	if !ok {
		ahttp.HTTPResponse(w, http.StatusInternalServerError, "Unable to obtain database from context")
		return
	}

	col, err := st.Coll(query.CollName)
	if err != nil {
		ahttp.HTTPResponse(w, http.StatusInternalServerError, "%v", err)
		return
	}

	collQuery := col.Find(query.Pattern)
	doc, err := query.One(collQuery)

	if err != nil {
		if db.IsNotFound(err) {
			ahttp.HTTPResponse(w, http.StatusNotFound, "Not found")
		} else {
			ahttp.HTTPResponse(w, http.StatusInternalServerError, "%v", err)
		}
		return
	}

	msg, err := json.Marshal(doc)
	if err != nil {
		ahttp.HTTPResponse(w, http.StatusInternalServerError, "Unable to marshal document")
		return
	}

	w.Write([]byte(`{"result":`))
	w.Write(msg)
	w.Write([]byte(`}`))
}
开发者ID:altlinux,项目名称:webery,代码行数:35,代码来源:api-get.go

示例4: AclGetHandler

// :WEBAPI:
// {
//   "url": "{schema}://{host}/api/v1/acl/{repo}/{type}/{name}",
//   "method": "GET",
//   "arguments": [
//     {"name": "repo", "type": "string", "description": "repository name"},
//     {"name": "type", "type": "string", "description": "type of object, can be 'package' or 'group'"},
//     {"name": "name", "type": "string", "description": "name of object"}
//   ],
//   "description": "Shows the ACL for the specified name in the repository"
// }
func AclGetHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	p, ok := ctx.Value("http.request.query.params").(*url.Values)
	if !ok {
		ahttp.HTTPResponse(w, http.StatusInternalServerError, "Unable to obtain params from context")
		return
	}

	apiGet(ctx, w, r, Query{
		CollName: "acl_" + p.Get("type"),
		Pattern: db.QueryDoc{
			"repo": p.Get("repo"),
			"name": p.Get("name"),
		},
		One: func(query db.Query) (interface{}, error) {
			var err error
			t := &acl.ACL{}

			if p.Get("type") == "groups" {
				if p.Get("name") == "nobody" || p.Get("name") == "everybody" {
					t.Name = p.Get("name")
					t.Repo = p.Get("repo")
					t.Members = make([]acl.Member, 0)
					return t, err
				}
			}

			err = query.One(t)
			return t, err
		},
	})
}
开发者ID:altlinux,项目名称:webery,代码行数:42,代码来源:acl.go

示例5: TaskListHandler

// :WEBAPI:
// {
//   "url": "{schema}://{host}/api/v1/tasks",
//   "method": "GET",
//   "description": "Returns list of tasks",
//   "parameters": [
//     {"name": "state", "type": "string", "description": "shows tasks with specified state",       "default": "NaN"},
//     {"name": "owner", "type": "string", "description": "shows tasks with specified owner",       "default": "NaN"},
//     {"name": "limit", "type": "number", "description": "shows only specified number of retults", "default": "1000"}
//   ]
// }
func TaskListHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	p, ok := ctx.Value("http.request.query.params").(*url.Values)
	if !ok {
		ahttp.HTTPResponse(w, http.StatusInternalServerError, "Unable to obtain params from context")
		return
	}

	q := db.QueryDoc{}

	if p.Get("owner") != "" {
		q["owner"] = p.Get("owner")
	}
	if p.Get("repo") != "" {
		q["repo"] = p.Get("repo")
	}
	if p.Get("state") != "" {
		q["state"] = p.Get("state")
	}

	apiSearch(ctx, w, r, []Query{
		Query{
			CollName: task.CollName,
			Sort:     []string{"taskid"},
			Pattern:  q,
			Iterator: func(iter db.Iter) interface{} {
				t := task.New()
				if !iter.Next(t) {
					return nil
				}
				return t
			},
		},
	})
}
开发者ID:altlinux,项目名称:webery,代码行数:45,代码来源:tasks.go

示例6: AclReposListHandler

// :WEBAPI:
// {
//   "url": "{schema}://{host}/api/v1/acl",
//   "method": "GET",
//   "description": "Returns list of supported repositories"
// }
func AclReposListHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	if cfg, ok := ctx.Value("app.config").(*config.Config); ok {
		msg, err := json.Marshal(cfg.Builder.Repos)
		if err != nil {
			ahttp.HTTPResponse(w, http.StatusBadRequest, "Unable to marshal json: %v", err)
			return
		}
		w.Write(msg)
		return
	}
	ahttp.HTTPResponse(w, http.StatusInternalServerError, "Unable to obtain config from context")
}
开发者ID:altlinux,项目名称:webery,代码行数:18,代码来源:acl.go

示例7: TaskUpdateHandler

// :WEBAPI:
// {
//   "url": "{schema}://{host}/api/v1/tasks/{taskid}",
//   "method": "POST",
//   "arguments": [
//     {"name": "taskid", "type": "integer", "description": "task number"}
//   ],
//   "description": "Updates existing task"
// }
func TaskUpdateHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	p, ok := ctx.Value("http.request.query.params").(*url.Values)
	if !ok {
		ahttp.HTTPResponse(w, http.StatusInternalServerError, "Unable to obtain params from context")
		return
	}

	st, ok := ctx.Value("app.database").(db.Session)
	if !ok {
		ahttp.HTTPResponse(w, http.StatusInternalServerError, "Unable to obtain database 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("TaskUpdateHandler: 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
	}

	taskID := task.MakeID(util.ToInt64(p.Get("task")))

	t, err := task.Read(st, taskID)
	if err != nil {
		if db.IsNotFound(err) {
			ahttp.HTTPResponse(w, http.StatusNotFound, "Not found")
		} else {
			ahttp.HTTPResponse(w, http.StatusInternalServerError, "Unable to read: %v", err)
		}
		return
	}

	t.TaskID.Set(util.ToInt64(p.Get("task")))

	if !t.TimeCreate.IsDefined() {
		t.TimeCreate.Set(time.Now().Unix())
	}

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

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

	ahttp.HTTPResponse(w, http.StatusOK, "OK")
}
开发者ID:altlinux,项目名称:webery,代码行数:62,代码来源:tasks.go

示例8: SubtaskUpdateHandler

// :WEBAPI:
// {
//   "url": "{schema}://{host}/api/v1/tasks/{taskid}/subtasks/{subtaskid}",
//   "method": "POST",
//   "arguments": [
//     {"name": "taskid",    "type": "integer", "description": "task number"},
//     {"name": "subtaskid", "type": "integer", "description": "subtask number"}
//   ],
//   "description": "Updates subtask in task"
// }
func SubtaskUpdateHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	p, ok := ctx.Value("http.request.query.params").(*url.Values)
	if !ok {
		ahttp.HTTPResponse(w, http.StatusInternalServerError, "Unable to obtain params from context")
		return
	}

	st, ok := ctx.Value("app.database").(db.Session)
	if !ok {
		ahttp.HTTPResponse(w, http.StatusInternalServerError, "Unable to obtain database from context")
		return
	}

	subtaskID := subtask.MakeID(util.ToInt64(p.Get("task")), util.ToInt64(p.Get("subtask")))

	t, err := subtask.Read(st, subtaskID)
	if err != nil {
		if db.IsNotFound(err) {
			ahttp.HTTPResponse(w, http.StatusNotFound, "Not found")
		} else {
			ahttp.HTTPResponse(w, http.StatusInternalServerError, "Unable to read: %v", err)
		}
		return
	}

	t.TaskID.Set(util.ToInt64(p.Get("task")))
	t.SubTaskID.Set(util.ToInt64(p.Get("subtask")))

	t.TaskID.Readonly(true)
	t.SubTaskID.Readonly(true)
	t.TimeCreate.Readonly(true)

	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).Debugf("SubtaskUpdateHandler: Request body: %s", string(msg))

	if err = json.Unmarshal(msg, t); err != nil {
		ahttp.HTTPResponse(w, http.StatusBadRequest, "Invalid JSON: %s", err)
		return
	}
	logger.GetHTTPEntry(ctx).WithFields(nil).Debugf("SubtaskUpdateHandler: SubTask: %+v", t)

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

	ahttp.HTTPResponse(w, http.StatusOK, "OK")
}
开发者ID:altlinux,项目名称:webery,代码行数:61,代码来源:subtasks.go

示例9: FileHandler

func FileHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	if cfg, ok := ctx.Value("app.config").(*config.Config); ok {
		path := r.URL.Path

		if _, err := os.Stat(cfg.Content.Path + path); err != nil {
			path = "/index.html"
		}

		http.ServeFile(w, r, cfg.Content.Path+path)
		return
	}
	ahttp.HTTPResponse(w, http.StatusInternalServerError, "Unable to obtain config from context")
	InternalServerErrorHandler(ctx, w, r)
}
开发者ID:altlinux,项目名称:webery,代码行数:14,代码来源:static.go

示例10: GetHTTPEntry

func GetHTTPEntry(ctx context.Context) *Entry {
	e := NewEntry()

	if v := ctx.Value("instance.id"); v != nil {
		e = e.WithField("http.request.id", v)
	}

	for _, k := range []string{"http.request.method", "http.request.remoteaddr", "http.request.length", "http.request.time"} {
		if v := ctx.Value(k); v != nil {
			e = e.WithField(k, v)
		}
	}
	return e
}
开发者ID:altlinux,项目名称:webery,代码行数:14,代码来源:logger.go

示例11: Handler

func Handler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	info, ok := ctx.Value("http.endpoints").(*EndpointsInfo)
	if !ok {
		ahttp.HTTPResponse(w, http.StatusInternalServerError, "Unable to obtain API information from context")
		InternalServerErrorHandler(ctx, w, r)
		return
	}

	p := r.URL.Query()

	for _, a := range info.Endpoints {
		match := a.Regexp.FindStringSubmatch(r.URL.Path)
		if match == nil {
			continue
		}

		for i, name := range a.Regexp.SubexpNames() {
			if i == 0 {
				continue
			}
			p.Set(name, match[i])
		}

		ctx = context.WithValue(ctx, "http.request.query.params", &p)

		var reqHandler ahttp.Handler

		if v, ok := a.Handlers[r.Method]; ok {
			reqHandler = v

			if a.NeedDBHandler {
				reqHandler = db.Handler(reqHandler)
			}

			if a.NeedJSONHandler {
				reqHandler = jsonresponse.Handler(reqHandler)
			}
		} else {
			reqHandler = NotAllowedHandler
		}

		reqHandler(ctx, w, r)
		return
	}

	// Never should be here
	NotFoundHandler(ctx, w, r)
}
开发者ID:altlinux,项目名称:webery,代码行数:48,代码来源:handlers.go

示例12: TaskCreateHandler

// :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")
}
开发者ID:altlinux,项目名称:webery,代码行数:54,代码来源:tasks.go

示例13: SubtaskGetHandler

// :WEBAPI:
// {
//   "url": "{schema}://{host}/api/v1/tasks/{taskid}/subtasks/{subtaskid}",
//   "method": "GET",
//   "arguments": [
//     {"name": "taskid",    "type": "integer", "description": "task number"},
//     {"name": "subtaskid", "type": "integer", "description": "subtask number"}
//   ],
//   "description": "Creates new subtask for specified task"
// }
func SubtaskGetHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	p, ok := ctx.Value("http.request.query.params").(*url.Values)
	if !ok {
		ahttp.HTTPResponse(w, http.StatusInternalServerError, "Unable to obtain params from context")
		return
	}

	apiGet(ctx, w, r, Query{
		CollName: subtask.CollName,
		Pattern:  subtask.MakeID(util.ToInt64(p.Get("task")), util.ToInt64(p.Get("subtask"))),
		One: func(query db.Query) (interface{}, error) {
			t := subtask.New()
			err := query.One(t)
			return t, err
		},
	})
}
开发者ID:altlinux,项目名称:webery,代码行数:27,代码来源:subtasks.go

示例14: SubtaskCreateHandler

// :WEBAPI:
// {
//   "url": "{schema}://{host}/api/v1/tasks/{taskid}/subtasks",
//   "method": "POST",
//   "arguments": [
//     {"name": "taskid", "type": "integer", "description": "task number"}
//   ],
//   "description": "Creates new subtask for specified task"
// }
func SubtaskCreateHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	p, ok := ctx.Value("http.request.query.params").(*url.Values)
	if !ok {
		ahttp.HTTPResponse(w, http.StatusInternalServerError, "Unable to obtain params 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).Debugf("SubtaskCreateHandler: Request body: %s", string(msg))

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

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

	if !t.Type.IsDefined() {
		t.Type.Set("unknown")
	}

	if !t.Status.IsDefined() {
		t.Status.Set("active")
	}

	t.TaskID.Set(util.ToInt64(p.Get("task")))
	t.TimeCreate.Set(time.Now().Unix())

	logger.GetHTTPEntry(ctx).WithFields(nil).Debugf("SubtaskCreateHandler: SubTask: %+v", t)

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

	ahttp.HTTPResponse(w, http.StatusOK, "OK")
}
开发者ID:altlinux,项目名称:webery,代码行数:53,代码来源:subtasks.go

示例15: writeTask

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
}
开发者ID:altlinux,项目名称:webery,代码行数:41,代码来源:tasks.go


注:本文中的github.com/altlinux/webery/pkg/context.Context类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。