本文整理汇总了Golang中github.com/app-kit/go-appkit.Request类的典型用法代码示例。如果您正苦于以下问题:Golang Request类的具体用法?Golang Request怎么用?Golang Request使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Request类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
示例16: 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
示例17: 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
示例18: Create
func Create(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),
}
}
fmt.Printf("data: %v | %+v\n\n", nil, request.GetData())
model, ok := request.GetData().(kit.Model)
if !ok {
return nil, apperror.New("invalid_data_no_model", "No model data in request.")
}
response := res.ApiCreate(model, request)
if response.GetError() == nil {
response.SetHttpStatus(201)
}
return response, nil
}
开发者ID:app-kit,项目名称:go-appkit,代码行数:24,代码来源:handlers.go
示例19: Find
func Find(res kit.Resource, request kit.Request) (kit.Response, apperror.Error) {
collection := res.Collection()
info := res.Backend().ModelInfo(collection)
var query *db.Query
jsonQuery := request.GetContext().String("query")
if jsonQuery != "" {
var rawQuery map[string]interface{}
if err := json.Unmarshal([]byte(jsonQuery), &rawQuery); err != nil {
return nil, apperror.Wrap(err, "invalid_query_json")
}
rawQuery["collection"] = collection
// A custom query was supplied.
// Try to parse the query.
var err apperror.Error
query, err = db.ParseQuery(res.Backend(), rawQuery)
if err != nil {
return nil, apperror.Wrap(err, "invalid_query", "", false)
}
}
if query == nil {
query = res.Backend().Q(collection)
}
// Check paging parameters.
var limit, offset int
context := request.GetContext()
if context.Has("limit") {
val, err := context.Int("limit")
if err != nil {
return nil, &apperror.Err{
Public: true,
Code: "non_numeric_limit_parameter",
Message: "The get query contains a non-numeric ?limit",
}
}
limit = val
}
if context.Has("offset") {
val, err := context.Int("offset")
if err != nil {
return nil, &apperror.Err{
Public: true,
Code: "non_numeric_offset_parameter",
Message: "The get query contains a non-numeric ?offset",
}
}
offset = val
}
var page, perPage int
if context.Has("page") {
val, err := context.Int("page")
if err != nil {
return nil, &apperror.Err{
Public: true,
Code: "non_numeric_page_parameter",
Message: "The get query contains a non-numeric ?page",
}
}
page = val
}
if context.Has("per_page") {
val, err := context.Int("per_page")
if err != nil {
return nil, &apperror.Err{
Public: true,
Code: "non_numeric_per_page_parameter",
Message: "The get query contains a non-numeric ?per_page",
}
}
perPage = val
}
if perPage > 0 {
limit = perPage
}
if page > 1 {
offset = (page - 1) * limit
}
if limit > 0 {
query.Limit(int(limit)).Offset(int(offset))
}
// Add joins.
if context.Has("joins") {
parts := strings.Split(context.String("joins"), ",")
for _, name := range parts {
//.........这里部分代码省略.........
开发者ID:app-kit,项目名称:go-appkit,代码行数:101,代码来源:handlers.go
示例20: RequestLoggerMiddleware
func RequestLoggerMiddleware(registry kit.Registry, r kit.Request, response kit.Response) (kit.Response, bool) {
// Calculate time taken.
rawStarted, ok1 := r.GetContext().Get("startTime")
rawFinished, ok2 := r.GetContext().Get("endTime")
timeTaken := int64(-1)
if ok1 && ok2 {
started := rawStarted.(time.Time)
finished := rawFinished.(time.Time)
timeTaken = int64(finished.Sub(started) / time.Millisecond)
}
// Log the request.
method := r.GetHttpMethod()
path := r.GetPath()
if response.GetError() != nil {
registry.Logger().WithFields(logrus.Fields{
"frontend": r.GetFrontend(),
"action": "request",
"method": method,
"path": path,
"status": response.GetHttpStatus(),
"err": response.GetError(),
"milliseconds": timeTaken,
}).Errorf("%v: %v - %v - %v", response.GetHttpStatus(), method, path, response.GetError())
} else {
registry.Logger().WithFields(logrus.Fields{
"frontend": r.GetFrontend(),
"action": "request",
"method": method,
"path": path,
"status": response.GetHttpStatus(),
"milliseconds": timeTaken,
}).Debugf("%v: %v - %v", response.GetHttpStatus(), method, path)
}
return nil, false
}
开发者ID:app-kit,项目名称:go-appkit,代码行数:39,代码来源:middlewares.go
注:本文中的github.com/app-kit/go-appkit.Request类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论