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


Golang go-appkit.Request类代码示例

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


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

示例1: HandleFind

func HandleFind(registry kit.Registry, request kit.Request) (kit.Response, bool) {
	collection := request.GetContext().MustString("collection")

	res := registry.Resource(collection)
	if res == nil || !res.IsPublic() {
		err := &apperror.Err{
			Code:    "unknown_resource",
			Message: fmt.Sprintf("The resource '%v' does not exist", collection),
		}
		return kit.NewErrorResponse(err), false
	}

	response, err := Find(res, request)
	if err != nil {
		response = kit.NewErrorResponse(err)
	}

	// If response contains a count and the request a "perPage" param, add a total_pages param
	// to meta.
	perPage, err2 := request.GetContext().Int("per_page")

	meta := response.GetMeta()
	if meta != nil && err2 == nil {
		count, ok := meta["count"]
		if ok {
			meta["total_pages"] = math.Ceil(float64(count.(int)) / float64(perPage))
		}
	}

	return response, false
}
开发者ID:app-kit,项目名称:go-appkit,代码行数:31,代码来源:handlers.go

示例2: RunMethod

func (a *App) RunMethod(name string, r kit.Request, responder func(kit.Response), withFinishedChannel bool) (chan bool, apperror.Error) {
	method := a.registry.Method(name)
	if method == nil {
		return nil, &apperror.Err{
			Code:    "unknown_method",
			Message: fmt.Sprintf("The method %v does not exist", name),
		}
	}

	if r.GetSession() == nil {
		session, err := a.UserService().StartSession(r.GetUser(), "")
		if err != nil {
			return nil, err
		}
		r.SetSession(session)
	}

	instance := NewMethodInstance(method, r, responder)

	if withFinishedChannel {
		c := make(chan bool)
		instance.finishedChannel = c
		return c, a.sessionManager.QueueMethod(r.GetSession(), instance)
	} else {
		return nil, a.sessionManager.QueueMethod(r.GetSession(), instance)
	}
}
开发者ID:app-kit,项目名称:go-appkit,代码行数:27,代码来源:app.go

示例3: notFoundHandler

func notFoundHandler(registry kit.Registry, r kit.Request) (kit.Response, bool) {
	httpRequest := r.GetHttpRequest()
	apiPrefix := "/" + registry.Config().UString("api.prefix", "api")
	isApiRequest := strings.HasPrefix(httpRequest.URL.Path, apiPrefix)

	// Try to render the page on the server, if enabled.
	if !isApiRequest {
		renderEnabled := registry.Config().UBool("serverRenderer.enabled", false)
		noRender := strings.Contains(httpRequest.URL.String(), "no-server-render")

		if renderEnabled && !noRender {
			return serverRenderer(registry, r), false
		}
	}

	// For non-api requests, render the default template.
	if !isApiRequest {
		tpl, err := getIndexTpl(registry)
		if err != nil {
			return kit.NewErrorResponse(err), false
		}
		return &kit.AppResponse{
			RawData: tpl,
		}, false
	}

	// For api requests, render the api not found error.
	return &kit.AppResponse{
		Error: &apperror.Err{
			Code:    "not_found",
			Message: "This api route does not exist",
		},
	}, false
}
开发者ID:app-kit,项目名称:go-appkit,代码行数:34,代码来源:api.go

示例4: ApiCreate

func (_ FilesResource) ApiCreate(res kit.Resource, obj kit.Model, r kit.Request) kit.Response {
	// Verify that tmp path is set either in metadata or on model.

	file := obj.(kit.File)
	if file.GetTmpPath() == "" {
		file.SetTmpPath(r.GetMeta().String("file"))
	}

	filePath := file.GetTmpPath()
	if filePath == "" {
		return kit.NewErrorResponse("no_tmp_path", "A tmp path must be set when creating a file", true)
	}

	tmpPath := getTmpPath(res)

	if !strings.HasPrefix(filePath, tmpPath) && filePath[0] != '/' {
		filePath = tmpPath + string(os.PathSeparator) + filePath
		file.SetTmpPath(filePath)
	}

	// Build the file, save it to backend and persist it to the db.
	err := res.Registry().FileService().BuildFile(file, r.GetUser(), true, true)
	if err != nil {
		kit.NewErrorResponse(err)
	}

	return &kit.AppResponse{
		Data: file,
	}
}
开发者ID:app-kit,项目名称:go-appkit,代码行数:30,代码来源:resource.go

示例5: ApiAlterQuery

func (PageResource) ApiAlterQuery(res kit.Resource, query db.Query, r kit.Request) apperror.Error {
	typ := r.GetContext().String("type")
	if typ != "" {
		query.Filter("type", typ)
	}
	return nil
}
开发者ID:app-kit,项目名称:go-appkit,代码行数:7,代码来源:resources.go

示例6: SerializeResponseMiddleware

func SerializeResponseMiddleware(registry kit.Registry, request kit.Request, response kit.Response) (kit.Response, bool) {
	// Try to serialize the reponse data.

	// Determine serializer.
	serializer := registry.DefaultSerializer()

	// Check if a custom serializer was specified.
	if name := request.GetContext().String("response-serializer"); name != "" {
		serializer = registry.Serializer(name)
		if serializer == nil {
			errResp := kit.NewErrorResponse("unknown_response_serializer", true)
			data, _ := serializer.MustSerializeResponse(errResp)
			errResp.SetData(data)
			return errResp, false
		}
	}

	// Set format in metadata.
	meta := response.GetMeta()
	if meta == nil {
		meta = make(map[string]interface{})
	}

	meta["format"] = serializer.Name()
	response.SetMeta(meta)

	data, err := serializer.MustSerializeResponse(response)
	if err != nil {
		registry.Logger().Errorf("Response serialization error: %v (%+v)", err, response)
	}
	response.SetData(data)

	return nil, false
}
开发者ID:app-kit,项目名称:go-appkit,代码行数:34,代码来源:middlewares.go

示例7: ApiCreate

// Creating a session is equivalent to logging in.
func (hooks SessionResourceHooks) ApiCreate(res kit.Resource, obj kit.Model, r kit.Request) kit.Response {
	userService := res.Registry().UserService()

	meta := r.GetMeta()

	isAnonymous, _ := meta.Bool("anonymous")

	// Find user.
	userIdentifier := meta.String("user")
	adaptor := meta.String("adaptor")
	data, _ := meta.Map("authData")

	var user kit.User
	if !isAnonymous {
		if adaptor == "" {
			return kit.NewErrorResponse("adaptor_missing", "Expected 'adaptor' in metadata.", true)
		}

		if data == nil {
			kit.NewErrorResponse("no_or_invalid_auth_data", "Expected 'authData' dictionary in metadata.")
		}

		var err apperror.Error
		user, err = userService.AuthenticateUser(userIdentifier, adaptor, data)
		if err != nil {
			return kit.NewErrorResponse(err)
		}
	}

	session, err := userService.StartSession(user, r.GetFrontend())
	if err != nil {
		return kit.NewErrorResponse(err)
	}

	responseMeta := make(map[string]interface{})

	if !isAnonymous {
		userData, err := res.Backend().ModelToMap(user, true, false)
		if err != nil {
			return kit.NewErrorResponse("marshal_error", err)
		}
		responseMeta["user"] = userData

		if user.GetProfile() != nil {
			profileData, err := res.Backend().ModelToMap(user.GetProfile(), true, false)
			if err != nil {
				return kit.NewErrorResponse("marshal_error", err)
			}
			responseMeta["profile"] = profileData
		}
	}

	return &kit.AppResponse{
		Data: session,
		Meta: responseMeta,
	}
}
开发者ID:app-kit,项目名称:go-appkit,代码行数:58,代码来源:resources.go

示例8: UnserializeRequest

// UnserializeRequest converts request data into a request object.
func (s *Serializer) UnserializeRequest(rawData interface{}, request kit.Request) apperror.Error {
	transData, err := s.UnserializeTransferData(rawData)
	if err != nil {
		return err
	}
	request.SetTransferData(transData)
	request.SetData(transData.GetData())
	return nil
}
开发者ID:app-kit,项目名称:go-appkit,代码行数:10,代码来源:jsonapi.go

示例9: ApiDelete

func (SessionResourceHooks) ApiDelete(res kit.Resource, id string, r kit.Request) kit.Response {
	if id != r.GetSession().GetStrId() {
		return kit.NewErrorResponse("permission_denied", "Permission denied", 403)
	}

	if err := res.Backend().Delete(r.GetSession()); err != nil {
		return kit.NewErrorResponse("db_delete_error", err, true)
	}

	return &kit.AppResponse{}
}
开发者ID:app-kit,项目名称:go-appkit,代码行数:11,代码来源:resources.go

示例10: ServerErrorMiddleware

func ServerErrorMiddleware(registry kit.Registry, r kit.Request, response kit.Response) (kit.Response, bool) {
	err := response.GetError()
	if err == nil {
		return nil, false
	}

	status := 500

	// If the error is an apperror, and it contains a status,
	// set it as the http status of the response.
	if apperr, ok := err.(apperror.Error); ok {
		if apperr.GetStatus() != 0 {
			status = apperr.GetStatus()
		}
	}

	response.SetHttpStatus(status)

	if response.GetRawData() != nil || response.GetRawDataReader() != nil {
		return nil, false
	}

	httpRequest := r.GetHttpRequest()
	apiPrefix := "/" + registry.Config().UString("api.prefix", "api")
	isApiRequest := strings.HasPrefix(httpRequest.URL.Path, apiPrefix)

	if isApiRequest {
		return nil, false
	}

	data := map[string]interface{}{"errors": []error{response.GetError()}}

	tpl := defaultErrorTpl()

	tplPath := registry.Config().UString("frontend.errorTemplate")
	if tplPath != "" {
		t, err := template.ParseFiles(tplPath)
		if err != nil {
			registry.Logger().Fatalf("Could not parse error template at '%v': %v", tplPath, err)
		} else {
			tpl = t
		}
	}

	var buffer *bytes.Buffer
	if err := tpl.Execute(buffer, data); err != nil {
		registry.Logger().Fatalf("Could not render error template: %v\n", err)
		response.SetRawData([]byte("Server error"))
	} else {
		response.SetRawData(buffer.Bytes())
	}

	return nil, false
}
开发者ID:app-kit,项目名称:go-appkit,代码行数:54,代码来源:api.go

示例11: HandleDelete

func HandleDelete(registry kit.Registry, request kit.Request) (kit.Response, bool) {
	collection := request.GetContext().MustString("collection")
	id := request.GetContext().MustString("id")

	res := registry.Resource(collection)
	if res == nil || !res.IsPublic() {
		resp := kit.NewErrorResponse("unknown_resource", fmt.Sprintf("The resource '%v' does not exist", collection))
		return resp, false
	}

	return res.ApiDelete(id, request), false
}
开发者ID:app-kit,项目名称:go-appkit,代码行数:12,代码来源:handlers.go

示例12: ApiPartialUpdate

func (res *Resource) ApiPartialUpdate(obj kit.Model, r kit.Request) kit.Response {
	if updateHook, ok := res.hooks.(ApiUpdateHook); ok {
		return updateHook.ApiUpdate(res, obj, r)
	}

	user := r.GetUser()
	err := res.PartialUpdate(obj, user)
	if err != nil {
		return kit.NewErrorResponse(err)
	}

	return &kit.AppResponse{
		Data: obj,
	}
}
开发者ID:app-kit,项目名称:go-appkit,代码行数:15,代码来源:resource.go

示例13: AuthenticationMiddleware

func AuthenticationMiddleware(registry kit.Registry, r kit.Request) (kit.Response, bool) {
	// Handle authentication.
	httpRequest := r.GetHttpRequest()
	userService := registry.UserService()

	if userService == nil {
		return nil, false
	}

	authHeader := httpRequest.Header.Get("Authentication")
	if authHeader == "" {
		return nil, false
	}

	// Check for basic auth.
	if strings.HasPrefix(authHeader, "Basic ") {
		str := authHeader[6:]
		data, err := base64.StdEncoding.DecodeString(str)
		if err != nil {
			return kit.NewErrorResponse("invalid_basic_auth"), false
		} else {
			parts := strings.Split(string(data), ":")
			if len(parts) == 2 {
				userIdentifier := parts[0]
				pw := parts[1]

				user, err := userService.AuthenticateUser(userIdentifier, "password", map[string]interface{}{"password": pw})
				if err != nil {
					return kit.NewErrorResponse(err), false
				}

				r.SetUser(user)
				return nil, false
			}
		}
	}

	// Check for auth token.
	if authHeader != "" {
		token := authHeader
		user, session, err := userService.VerifySession(token)
		if err == nil {
			r.SetUser(user)
			r.SetSession(session)

			return nil, false
		} else {
			return kit.NewErrorResponse(err), false
		}
	}

	return nil, false
}
开发者ID:app-kit,项目名称:go-appkit,代码行数:53,代码来源:api.go

示例14: Update

func Update(registry kit.Registry, request kit.Request) (kit.Response, apperror.Error) {
	collection := request.GetContext().MustString("collection")

	res := registry.Resource(collection)
	if res == nil || !res.IsPublic() {
		return nil, &apperror.Err{
			Code:    "unknown_resource",
			Message: fmt.Sprintf("The resource '%v' does not exist", collection),
		}
	}

	model, ok := request.GetData().(kit.Model)
	if !ok {
		return nil, apperror.New("invalid_data_no_model", "Node model data in request.")
	}

	response := res.ApiUpdate(model, request)

	return response, nil
}
开发者ID:app-kit,项目名称:go-appkit,代码行数:20,代码来源:handlers.go

示例15: ApiDelete

func (res *Resource) ApiDelete(id string, r kit.Request) kit.Response {
	if deleteHook, ok := res.hooks.(ApiDeleteHook); ok {
		return deleteHook.ApiDelete(res, id, r)
	}

	oldObj, err := res.FindOne(id)
	if err != nil {
		return kit.NewErrorResponse(err)
	} else if oldObj == nil {
		return kit.NewErrorResponse("not_found", "")
	}

	user := r.GetUser()
	if err := res.Delete(oldObj, user); err != nil {
		return kit.NewErrorResponse(err)
	}

	return &kit.AppResponse{
		Data: oldObj,
	}
}
开发者ID:app-kit,项目名称:go-appkit,代码行数:21,代码来源:resource.go


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