當前位置: 首頁>>代碼示例>>Golang>>正文


Golang go-appkit.NewErrorResponse函數代碼示例

本文整理匯總了Golang中github.com/app-kit/go-appkit.NewErrorResponse函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewErrorResponse函數的具體用法?Golang NewErrorResponse怎麽用?Golang NewErrorResponse使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了NewErrorResponse函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: ApiFindOne

// ApiFindOne verifies the session and returns user and profile in meta if valid.
func (SessionResourceHooks) ApiFindOne(res kit.Resource, rawId string, r kit.Request) kit.Response {
	if rawId == "" {
		return kit.NewErrorResponse("empty_token", "Empty token")
	}

	userService := res.Registry().UserService()

	user, session, err := userService.VerifySession(rawId)
	if err != nil {
		return kit.NewErrorResponse(err)
	}

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

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

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

	return &kit.AppResponse{
		Data: session,
		Meta: meta,
	}
}
開發者ID:app-kit,項目名稱:go-appkit,代碼行數:36,代碼來源:resources.go

示例2: 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

示例3: 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

示例4: 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

示例5: 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

示例6: ApiCreate

func (hooks UserResourceHooks) ApiCreate(res kit.Resource, obj kit.Model, r kit.Request) kit.Response {
	meta := r.GetMeta()

	adaptor := meta.String("adaptor")
	if adaptor == "" {
		return kit.NewErrorResponse("adaptor_missing", "Expected 'adaptor' in metadata.", true)
	}

	rawData, ok := meta.Get("authData")
	if !ok {
		return kit.NewErrorResponse("auth_data_missing", "Expected 'authData' in metadata.", true)
	}

	data, ok := rawData.(map[string]interface{})
	if !ok {
		return kit.NewErrorResponse("invalid_auth_data", "Invalid auth data: expected dictionary", true)
	}

	user := obj.(kit.User)

	service := res.Registry().UserService()

	// If a profile model was registered, and profile data is in meta,
	// create the profile model.
	if profiles := service.ProfileResource(); profiles != nil {
		profile := profiles.CreateModel().(kit.UserProfile)

		if rawData, ok := meta.Get("profile"); ok {
			if data, ok := rawData.(map[string]interface{}); ok {
				// Profile data present in meta.
				// Update profile with data.
				if err := res.ModelInfo().UpdateModelFromData(profile, data); err != nil {
					return kit.NewErrorResponse("invalid_profile_data", "Invalid profile data.", err, true)
				}
			}
		}

		user.SetProfile(profile)
	}

	if err := service.CreateUser(user, adaptor, data); err != nil {
		return kit.NewErrorResponse(err)
	}

	return &kit.AppResponse{
		Data: user,
	}
}
開發者ID:app-kit,項目名稱:go-appkit,代碼行數:48,代碼來源:resources.go

示例7: 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

示例8: 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

示例9: HandleUpdate

func HandleUpdate(registry kit.Registry, request kit.Request) (kit.Response, bool) {
	response, err := Update(registry, request)
	if err != nil {
		return kit.NewErrorResponse(err), false
	}

	return response, false
}
開發者ID:app-kit,項目名稱:go-appkit,代碼行數:8,代碼來源:handlers.go

示例10: UnserializeRequestMiddleware

func UnserializeRequestMiddleware(registry kit.Registry, request kit.Request) (kit.Response, bool) {
	// Try to parse json in body. Ignore error since body might not contain json.
	contentType := request.GetHttpRequest().Header.Get("Content-Type")
	if strings.Contains(contentType, "json") {
		// Only read the HTTP body automatically for json content type requests,
		// since some handlers might need to read it themselfes (see the files package resource).
		if err := request.ReadHttpBody(); err != nil {
			return kit.NewErrorResponse(err, "http_body_read_error"), false
		} else {
			if request.GetRawData() != nil {
				if err := request.ParseJsonData(); err != nil {
					return kit.NewErrorResponse(err, "invalid_json_body", true), false
				}

				if request.GetData() != nil {
					// Successfully parsed json body.

					// Now try to unserialize.

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

					// Check if a custom serializer was specified.
					if name := request.GetContext().String("request-serializer"); name != "" {
						serializer = registry.Serializer(name)
					}

					if serializer == nil {
						return kit.NewErrorResponse("unknown_serializer", fmt.Sprintf("The specified request serializer does not exist")), false
					} else {
						if err := request.Unserialize(serializer); err != nil {
							return kit.NewErrorResponse(err, "request_unserialize_error", true), false
						}
					}
				}
			}
		}
	}

	return nil, false
}
開發者ID:app-kit,項目名稱:go-appkit,代碼行數:41,代碼來源:api.go

示例11: Methods

func (PageResource) Methods(res kit.Resource) []kit.Method {

	publish := &methods.Method{
		Name:     "cms.page.publish",
		Blocking: true,
		Handler: func(registry kit.Registry, r kit.Request, unblock func()) kit.Response {
			user := r.GetUser()
			if user == nil || !user.HasRole("admin") {
				return kit.NewErrorResponse("permission_denied")
			}

			id := utils.GetMapStringKey(r.GetData(), "id")

			if id == "" {
				return kit.NewErrorResponse("no_id_in_data", "Expected 'id' key in data.")
			}

			rawPage, err := res.Backend().FindOne("pages", id)
			if err != nil {
				return kit.NewErrorResponse("db_error", err)
			} else if rawPage == nil {
				return kit.NewErrorResponse("not_found", "The specified page id does not exist.")
			}

			err = res.ModelInfo().UpdateModelFromData(rawPage, map[string]interface{}{
				"published":    true,
				"published_at": time.Now(),
			})

			if err != nil {
				return kit.NewErrorResponse("db_error", err)
			}

			return &kit.AppResponse{
				Data: map[string]interface{}{"success": true},
			}
		},
	}

	return []kit.Method{publish}
}
開發者ID:app-kit,項目名稱:go-appkit,代碼行數:41,代碼來源:resources.go

示例12: 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

示例13: 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

示例14: UnserializerMiddleware

func UnserializerMiddleware(registry kit.Registry, request kit.Request) (kit.Response, bool) {
	serializer := registry.DefaultSerializer()

	// Try to find custom serializer.
	data, ok := request.GetData().(map[string]interface{})
	if ok {
		name, ok := data["request_serializer"].(string)
		if ok {
			s := registry.Serializer(name)
			if s == nil {
				resp := kit.NewErrorResponse("unknown_request_serializer", fmt.Sprintf("The given request serializer %v does not exist", name))
				return resp, false
			} else {
				serializer = s
			}
		}
	}

	if err := serializer.UnserializeRequest(request.GetData(), request); err != nil {
		return kit.NewErrorResponse(err), false
	}

	return nil, false
}
開發者ID:app-kit,項目名稱:go-appkit,代碼行數:24,代碼來源:wamp.go

示例15: ApiFindOne

func (res *Resource) ApiFindOne(rawId string, r kit.Request) kit.Response {
	hook, ok := res.hooks.(ApiFindOneHook)
	if ok {
		return hook.ApiFindOne(res, rawId, r)
	}

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

	user := r.GetUser()
	if allowFind, ok := res.hooks.(AllowFindHook); ok {
		if !allowFind.AllowFind(res, result, user) {
			return kit.NewErrorResponse("permission_denied", "")
		}
	}

	return &kit.AppResponse{
		Data: result,
	}
}
開發者ID:app-kit,項目名稱:go-appkit,代碼行數:24,代碼來源:resource.go


注:本文中的github.com/app-kit/go-appkit.NewErrorResponse函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。