• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang resource.Resource类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: getSubResourceResolver

func getSubResourceResolver(r *resource.Resource) graphql.FieldResolveFn {
	return func(p graphql.ResolveParams) (interface{}, error) {
		parent, ok := p.Source.(map[string]interface{})
		if !ok {
			return nil, nil
		}
		lookup, page, perPage, err := listParamResolver(r, p, nil)
		if err != nil {
			return nil, err
		}
		// Limit the connection to parent's owned
		lookup.AddQuery(schema.Query{
			schema.Equal{
				Field: r.ParentField(),
				Value: parent["id"],
			},
		})
		list, err := r.Find(p.Context, lookup, page, perPage)
		if err != nil {
			return nil, err
		}
		result := make([]map[string]interface{}, len(list.Items))
		for i, item := range list.Items {
			result[i] = item.Payload
		}
		return result, nil
	}
}
开发者ID:rs,项目名称:rest-layer,代码行数:28,代码来源:types.go


示例2: addConnections

// addConnections adds connections fields to the object afterward to prevent from dead loops
func (t types) addConnections(o *graphql.Object, idx resource.Index, r *resource.Resource) {
	// Add sub field references
	for name, def := range r.Schema().Fields {
		if ref, ok := def.Validator.(*schema.Reference); ok {
			sr, found := idx.GetResource(ref.Path, nil)
			if !found {
				log.Panicf("resource reference not found: %s", ref.Path)
			}
			o.AddFieldConfig(name, &graphql.Field{
				Description: def.Description,
				Type:        t.getObjectType(idx, sr),
				Args:        getFArgs(def.Params),
				Resolve:     getSubFieldResolver(name, sr, def),
			})
		}
	}
	// Add sub resources
	for _, sr := range r.GetResources() {
		name := sr.Name()
		o.AddFieldConfig(name, &graphql.Field{
			Description: fmt.Sprintf("Connection to %s", name),
			Type:        graphql.NewList(t.getObjectType(idx, sr)),
			Args:        listArgs,
			Resolve:     getSubResourceResolver(sr),
		})
	}
}
开发者ID:rs,项目名称:rest-layer,代码行数:28,代码来源:types.go


示例3: NewBasicAuthHandler

// NewBasicAuthHandler handles basic HTTP auth against the provided user resource
func NewBasicAuthHandler(users *resource.Resource) func(next http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if u, p, ok := r.BasicAuth(); ok {
				// Lookup the user by its id
				ctx := r.Context()
				user, err := users.Get(ctx, u)
				if user != nil && err == resource.ErrUnauthorized {
					// Ignore unauthorized errors set by ourselves
					err = nil
				}
				if err != nil {
					// If user resource storage handler returned an error, respond with an error
					if err == resource.ErrNotFound {
						http.Error(w, "Invalid credential", http.StatusForbidden)
					} else {
						http.Error(w, err.Error(), http.StatusInternalServerError)
					}
					return
				}
				if schema.VerifyPassword(user.Payload["password"], []byte(p)) {
					// Store the auth user into the context for later use
					r = r.WithContext(NewContextWithUser(ctx, user))
					next.ServeHTTP(w, r)
					return
				}
			}
			// Stop the middleware chain and return a 401 HTTP error
			w.Header().Set("WWW-Authenticate", `Basic realm="API"`)
			http.Error(w, "Please provide proper credentials", http.StatusUnauthorized)
		})
	}
}
开发者ID:rs,项目名称:rest-layer,代码行数:34,代码来源:main.go


示例4: NewJWTHandler

// NewJWTHandler parse and validates JWT token if present and store it in the net/context
func NewJWTHandler(users *resource.Resource, jwtKeyFunc jwt.Keyfunc) func(next http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			token, err := request.ParseFromRequest(r, request.OAuth2Extractor, jwtKeyFunc)
			if err == request.ErrNoTokenInRequest {
				// If no token is found, let REST Layer hooks decide if the resource is public or not
				next.ServeHTTP(w, r)
				return
			}
			if err != nil || !token.Valid {
				// Here you may want to return JSON error
				http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
				return
			}
			claims := token.Claims.(jwt.MapClaims)
			userID, ok := claims["user_id"].(string)
			if !ok || userID == "" {
				// The provided token is malformed, user_id claim is missing
				http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
				return
			}
			// Lookup the user by its id
			ctx := r.Context()
			user, err := users.Get(ctx, userID)
			if user != nil && err == resource.ErrUnauthorized {
				// Ignore unauthorized errors set by ourselves (see AuthResourceHook)
				err = nil
			}
			if err != nil {
				// If user resource storage handler returned an error, respond with an error
				if err == resource.ErrNotFound {
					http.Error(w, "Invalid credential", http.StatusForbidden)
				} else {
					http.Error(w, err.Error(), http.StatusInternalServerError)
				}
				return
			}
			// Store it into the request's context
			ctx = NewContextWithUser(ctx, user)
			r = r.WithContext(ctx)
			// If xlog is setup, store the user as logger field
			xlog.FromContext(ctx).SetField("user_id", user.ID)
			next.ServeHTTP(w, r)
		})
	}
}
开发者ID:rs,项目名称:rest-layer,代码行数:47,代码来源:main.go


示例5: getGetQuery

func (t types) getGetQuery(idx resource.Index, r *resource.Resource) *graphql.Field {
	return &graphql.Field{
		Description: fmt.Sprintf("Get %s by id", r.Name()),
		Type:        t.getObjectType(idx, r),
		Args: graphql.FieldConfigArgument{
			"id": &graphql.ArgumentConfig{
				Type: graphql.String,
			},
		},
		Resolve: func(p graphql.ResolveParams) (interface{}, error) {
			id, ok := p.Args["id"].(string)
			if !ok {
				return nil, nil
			}
			item, err := r.Get(p.Context, id)
			if err != nil {
				return nil, err
			}
			return item.Payload, nil
		},
	}
}
开发者ID:rs,项目名称:rest-layer,代码行数:22,代码来源:query.go


示例6: getListQuery

func (t types) getListQuery(idx resource.Index, r *resource.Resource, params url.Values) *graphql.Field {
	return &graphql.Field{
		Description: fmt.Sprintf("Get a list of %s", r.Name()),
		Type:        graphql.NewList(t.getObjectType(idx, r)),
		Args:        listArgs,
		Resolve: func(p graphql.ResolveParams) (interface{}, error) {
			lookup, page, perPage, err := listParamResolver(r, p, params)
			if err != nil {
				return nil, err
			}
			list, err := r.Find(p.Context, lookup, page, perPage)
			if err != nil {
				return nil, err
			}
			result := make([]map[string]interface{}, len(list.Items))
			for i, item := range list.Items {
				result[i] = item.Payload
			}
			return result, nil
		},
	}
}
开发者ID:rs,项目名称:rest-layer,代码行数:22,代码来源:query.go


示例7: getSubFieldResolver

func getSubFieldResolver(parentField string, r *resource.Resource, f schema.Field) graphql.FieldResolveFn {
	s, serialize := f.Validator.(schema.FieldSerializer)
	return func(p graphql.ResolveParams) (data interface{}, err error) {
		parent, ok := p.Source.(map[string]interface{})
		if !ok {
			return nil, nil
		}
		var item *resource.Item
		// Get sub field resource
		item, err = r.Get(p.Context, parent[parentField])
		if err != nil {
			return nil, err
		}
		data = item.Payload
		if f.Handler != nil {
			data, err = f.Handler(p.Context, data, p.Args)
		}
		if err == nil && serialize {
			data, err = s.Serialize(data)
		}
		return data, err
	}
}
开发者ID:rs,项目名称:rest-layer,代码行数:23,代码来源:types.go


示例8: listParamResolver

func listParamResolver(r *resource.Resource, p graphql.ResolveParams, params url.Values) (lookup *resource.Lookup, page int, perPage int, err error) {
	page = 1
	// Default value on non HEAD request for perPage is -1 (pagination disabled)
	perPage = -1
	if l := r.Conf().PaginationDefaultLimit; l > 0 {
		perPage = l
	}
	if p, ok := p.Args["page"].(string); ok && p != "" {
		i, err := strconv.ParseUint(p, 10, 32)
		if err != nil {
			return nil, 0, 0, errors.New("invalid `limit` parameter")
		}
		page = int(i)
	}
	if l, ok := p.Args["limit"].(string); ok && l != "" {
		i, err := strconv.ParseUint(l, 10, 32)
		if err != nil {
			return nil, 0, 0, errors.New("invalid `limit` parameter")
		}
		perPage = int(i)
	}
	if perPage == -1 && page != 1 {
		return nil, 0, 0, errors.New("cannot use `page' parameter with no `limit' paramter on a resource with no default pagination size")
	}
	lookup = resource.NewLookup()
	if sort, ok := p.Args["sort"].(string); ok && sort != "" {
		if err := lookup.SetSort(sort, r.Validator()); err != nil {
			return nil, 0, 0, fmt.Errorf("invalid `sort` parameter: %v", err)
		}
	}
	if filter, ok := p.Args["filter"].(string); ok && filter != "" {
		if err := lookup.AddFilter(filter, r.Validator()); err != nil {
			return nil, 0, 0, fmt.Errorf("invalid `filter` parameter: %v", err)
		}
	}
	if params != nil {
		if filter := params.Get("filter"); filter != "" {
			if err := lookup.AddFilter(filter, r.Validator()); err != nil {
				return nil, 0, 0, fmt.Errorf("invalid `filter` parameter: %v", err)
			}
		}
	}
	return
}
开发者ID:rs,项目名称:rest-layer,代码行数:44,代码来源:query.go


示例9: getObjectType

// getObjectType returns a graphql object type definition from a REST layer schema
func (t types) getObjectType(idx resource.Index, r *resource.Resource) *graphql.Object {
	// Memoize types by their name so we don't create several instance of the same resource
	name := r.Name()
	o := t[name]
	if o == nil {
		o = graphql.NewObject(graphql.ObjectConfig{
			Name:        name,
			Description: r.Schema().Description,
			Fields:      getFields(idx, r.Schema()),
		})
		t[name] = o
		t.addConnections(o, idx, r)
	}
	return o
}
开发者ID:rs,项目名称:rest-layer,代码行数:16,代码来源:types.go



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang schema.Validator类代码示例发布时间:2022-05-28
下一篇:
Golang resource.Lookup类代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap