本文整理匯總了Golang中github.com/go-openapi/errors.New函數的典型用法代碼示例。如果您正苦於以下問題:Golang New函數的具體用法?Golang New怎麽用?Golang New使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了New函數的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: BindRequest
// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *UploadTaskFileParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {
var res []error
o.HTTPRequest = r
if err := r.ParseMultipartForm(32 << 20); err != nil {
if err != http.ErrNotMultipart {
return err
} else if err := r.ParseForm(); err != nil {
return err
}
}
fds := runtime.Values(r.Form)
fdDescription, fdhkDescription, _ := fds.GetOK("description")
if err := o.bindDescription(fdDescription, fdhkDescription, route.Formats); err != nil {
res = append(res, err)
}
file, fileHeader, err := r.FormFile("file")
if err != nil {
res = append(res, errors.New(400, "reading file %q failed: %v", "file", err))
} else {
o.File = runtime.File{Data: file, Header: fileHeader}
}
rID, rhkID, _ := route.Params.GetOK("id")
if err := o.bindID(rID, rhkID, route.Formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
示例2: APIKeyAuth
// APIKeyAuth creates an authenticator that uses a token for authorization.
// This token can be obtained from either a header or a query string
func APIKeyAuth(name, in string, authenticate TokenAuthentication) runtime.Authenticator {
inl := strings.ToLower(in)
if inl != "query" && inl != "header" {
// panic because this is most likely a typo
panic(errors.New(500, "api key auth: in value needs to be either \"query\" or \"header\"."))
}
var getToken func(*http.Request) string
switch inl {
case "header":
getToken = func(r *http.Request) string { return r.Header.Get(name) }
case "query":
getToken = func(r *http.Request) string { return r.URL.Query().Get(name) }
}
return httpAuthenticator(func(r *http.Request) (bool, interface{}, error) {
token := getToken(r)
if token == "" {
return false, nil, nil
}
p, err := authenticate(token)
return true, p, err
})
}
示例3: Bind
// Bind perform the databinding and validation
func (o *untypedRequestBinder) Bind(request *http.Request, routeParams RouteParams, consumer runtime.Consumer, data interface{}) error {
val := reflect.Indirect(reflect.ValueOf(data))
isMap := val.Kind() == reflect.Map
var result []error
for fieldName, param := range o.Parameters {
binder := o.paramBinders[fieldName]
var target reflect.Value
if !isMap {
binder.Name = fieldName
target = val.FieldByName(fieldName)
}
if isMap {
tpe := binder.Type()
if tpe == nil {
if param.Schema.Type.Contains("array") {
tpe = reflect.TypeOf([]interface{}{})
} else {
tpe = reflect.TypeOf(map[string]interface{}{})
}
}
target = reflect.Indirect(reflect.New(tpe))
}
if !target.IsValid() {
result = append(result, errors.New(500, "parameter name %q is an unknown field", binder.Name))
continue
}
if err := binder.Bind(request, routeParams, consumer, target); err != nil {
result = append(result, err)
continue
}
if binder.validator != nil {
rr := binder.validator.Validate(target.Interface())
if rr != nil && rr.HasErrors() {
result = append(result, rr.AsError())
}
}
if isMap {
val.SetMapIndex(reflect.ValueOf(param.Name), target)
}
}
if len(result) > 0 {
return errors.CompositeValidationError(result...)
}
return nil
}
示例4: addItem
func addItem(item *models.Item) error {
if item == nil {
return errors.New(500, "item must be present")
}
itemsLock.Lock()
defer itemsLock.Unlock()
newID := newItemID()
item.ID = newID
items[newID] = item
return nil
}
示例5: BindValidRequest
// BindValidRequest binds a params object to a request but only when the request is valid
// if the request is not valid an error will be returned
func (c *Context) BindValidRequest(request *http.Request, route *MatchedRoute, binder RequestBinder) error {
var res []error
requestContentType := "*/*"
// check and validate content type, select consumer
if runtime.HasBody(request) {
ct, _, err := runtime.ContentType(request.Header)
if err != nil {
res = append(res, err)
} else {
if err := validateContentType(route.Consumes, ct); err != nil {
res = append(res, err)
}
if len(res) == 0 {
cons, ok := route.Consumers[ct]
if !ok {
res = append(res, errors.New(500, "no consumer registered for %s", ct))
} else {
route.Consumer = cons
requestContentType = ct
}
}
}
}
// check and validate the response format
if len(res) == 0 && runtime.HasBody(request) {
if str := NegotiateContentType(request, route.Produces, requestContentType); str == "" {
res = append(res, errors.InvalidResponseFormat(request.Header.Get(runtime.HeaderAccept), route.Produces))
}
}
// now bind the request with the provided binder
// it's assumed the binder will also validate the request and return an error if the
// request is invalid
if binder != nil && len(res) == 0 {
if err := binder.BindRequest(request, route); err != nil {
return err
}
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
示例6: updateItem
func updateItem(id int64, item *models.Item) error {
if item == nil {
return errors.New(500, "item must be present")
}
itemsLock.Lock()
defer itemsLock.Unlock()
_, exists := items[id]
if !exists {
return errors.NotFound("not found: item %d", id)
}
item.ID = id
items[id] = item
return nil
}
示例7: unmarshalPricingComponent
func unmarshalPricingComponent(data []byte, consumer runtime.Consumer) (PricingComponent, error) {
buf := bytes.NewBuffer(data)
buf2 := bytes.NewBuffer(data)
// the first time this is read is to fetch the value of the @type property.
var getType struct {
AtType string `json:"@type"`
}
if err := consumer.Consume(buf, &getType); err != nil {
return nil, err
}
if err := validate.RequiredString("@type", "body", getType.AtType); err != nil {
return nil, err
}
// The value of @type is used to determine which type to create and unmarshal the data into
switch getType.AtType {
case "flatPricingComponent":
var result FlatPricingComponent
if err := consumer.Consume(buf2, &result); err != nil {
return nil, err
}
return &result, nil
case "tieredPricingComponent":
var result TieredPricingComponent
if err := consumer.Consume(buf2, &result); err != nil {
return nil, err
}
return &result, nil
case "tieredVolumePricingComponent":
var result TieredVolumePricingComponent
if err := consumer.Consume(buf2, &result); err != nil {
return nil, err
}
return &result, nil
}
return nil, errors.New(422, "invalid @type value: %q", getType.AtType)
}
示例8: validateSchemaItems
func (s *SpecValidator) validateSchemaItems(schema spec.Schema, prefix, opID string) error {
if !schema.Type.Contains("array") {
return nil
}
if schema.Items == nil || schema.Items.Len() == 0 {
return errors.New(422, "%s for %q is a collection without an element type", prefix, opID)
}
schemas := schema.Items.Schemas
if schema.Items.Schema != nil {
schemas = []spec.Schema{*schema.Items.Schema}
}
for _, sch := range schemas {
if err := s.validateSchemaItems(sch, prefix, opID); err != nil {
return err
}
}
return nil
}
示例9: contentType
func (v *validation) contentType() {
if len(v.result) == 0 && runtime.HasBody(v.request) {
ct, _, err := v.context.ContentType(v.request)
if err != nil {
v.result = append(v.result, err)
}
if len(v.result) == 0 {
if err := validateContentType(v.route.Consumes, ct); err != nil {
v.result = append(v.result, err)
}
}
if ct != "" && v.route.Consumer == nil {
cons, ok := v.route.Consumers[ct]
if !ok {
v.result = append(v.result, errors.New(500, "no consumer registered for %s", ct))
} else {
v.route.Consumer = cons
}
}
}
}
示例10: Respond
// Respond renders the response after doing some content negotiation
func (c *Context) Respond(rw http.ResponseWriter, r *http.Request, produces []string, route *MatchedRoute, data interface{}) {
offers := []string{}
for _, mt := range produces {
if mt != c.api.DefaultProduces() {
offers = append(offers, mt)
}
}
// the default producer is last so more specific producers take precedence
offers = append(offers, c.api.DefaultProduces())
format := c.ResponseFormat(r, offers)
rw.Header().Set(runtime.HeaderContentType, format)
if resp, ok := data.(Responder); ok {
producers := route.Producers
prod, ok := producers[format]
if !ok {
prods := c.api.ProducersFor([]string{c.api.DefaultProduces()})
pr, ok := prods[c.api.DefaultProduces()]
if !ok {
panic(errors.New(http.StatusInternalServerError, "can't find a producer for "+format))
}
prod = pr
}
resp.WriteResponse(rw, prod)
return
}
if err, ok := data.(error); ok {
if format == "" {
rw.Header().Set(runtime.HeaderContentType, runtime.JSONMime)
}
if route == nil || route.Operation == nil {
c.api.ServeErrorFor("")(rw, r, err)
return
}
c.api.ServeErrorFor(route.Operation.ID)(rw, r, err)
return
}
if route == nil || route.Operation == nil {
rw.WriteHeader(200)
if r.Method == "HEAD" {
return
}
producers := c.api.ProducersFor(offers)
prod, ok := producers[format]
if !ok {
panic(errors.New(http.StatusInternalServerError, "can't find a producer for "+format))
}
if err := prod.Produce(rw, data); err != nil {
panic(err) // let the recovery middleware deal with this
}
return
}
if _, code, ok := route.Operation.SuccessResponse(); ok {
rw.WriteHeader(code)
if code == 204 || r.Method == "HEAD" {
return
}
producers := route.Producers
prod, ok := producers[format]
if !ok {
if !ok {
prods := c.api.ProducersFor([]string{c.api.DefaultProduces()})
pr, ok := prods[c.api.DefaultProduces()]
if !ok {
panic(errors.New(http.StatusInternalServerError, "can't find a producer for "+format))
}
prod = pr
}
}
if err := prod.Produce(rw, data); err != nil {
panic(err) // let the recovery middleware deal with this
}
return
}
c.api.ServeErrorFor(route.Operation.ID)(rw, r, errors.New(http.StatusInternalServerError, "can't produce response"))
}