How to use Resolve method of loader Package

Best K6 code snippet using loader.Resolve

loader.go

Source:loader.go Github

copy

Full Screen

...16)17func foundUnresolvedRef(ref string) error {18 return fmt.Errorf("found unresolved ref: %q", ref)19}20func failedToResolveRefFragmentPart(value, what string) error {21 return fmt.Errorf("failed to resolve %q in fragment in URI: %q", what, value)22}23// Loader helps deserialize an OpenAPIv3 document24type Loader struct {25 // IsExternalRefsAllowed enables visiting other files26 IsExternalRefsAllowed bool27 // ReadFromURIFunc allows overriding the any file/URL reading func28 ReadFromURIFunc func(loader *Loader, url *url.URL) ([]byte, error)29 Context context.Context30 rootDir string31 visitedPathItemRefs map[string]struct{}32 visitedDocuments map[string]*T33 visitedExample map[*Example]struct{}34 visitedHeader map[*Header]struct{}35 visitedLink map[*Link]struct{}36 visitedParameter map[*Parameter]struct{}37 visitedRequestBody map[*RequestBody]struct{}38 visitedResponse map[*Response]struct{}39 visitedSchema map[*Schema]struct{}40 visitedSecurityScheme map[*SecurityScheme]struct{}41}42// NewLoader returns an empty Loader43func NewLoader() *Loader {44 return &Loader{}45}46func (loader *Loader) resetVisitedPathItemRefs() {47 loader.visitedPathItemRefs = make(map[string]struct{})48}49// LoadFromURI loads a spec from a remote URL50func (loader *Loader) LoadFromURI(location *url.URL) (*T, error) {51 loader.resetVisitedPathItemRefs()52 return loader.loadFromURIInternal(location)53}54// LoadFromFile loads a spec from a local file path55func (loader *Loader) LoadFromFile(location string) (*T, error) {56 loader.rootDir = path.Dir(location)57 return loader.LoadFromURI(&url.URL{Path: filepath.ToSlash(location)})58}59func (loader *Loader) loadFromURIInternal(location *url.URL) (*T, error) {60 data, err := loader.readURL(location)61 if err != nil {62 return nil, err63 }64 return loader.loadFromDataWithPathInternal(data, location)65}66func (loader *Loader) allowsExternalRefs(ref string) (err error) {67 if !loader.IsExternalRefsAllowed {68 err = fmt.Errorf("encountered disallowed external reference: %q", ref)69 }70 return71}72// loadSingleElementFromURI reads the data from ref and unmarshals to the passed element.73func (loader *Loader) loadSingleElementFromURI(ref string, rootPath *url.URL, element interface{}) (*url.URL, error) {74 if err := loader.allowsExternalRefs(ref); err != nil {75 return nil, err76 }77 parsedURL, err := url.Parse(ref)78 if err != nil {79 return nil, err80 }81 if fragment := parsedURL.Fragment; fragment != "" {82 return nil, fmt.Errorf("unexpected ref fragment %q", fragment)83 }84 resolvedPath, err := resolvePath(rootPath, parsedURL)85 if err != nil {86 return nil, fmt.Errorf("could not resolve path: %v", err)87 }88 data, err := loader.readURL(resolvedPath)89 if err != nil {90 return nil, err91 }92 if err := yaml.Unmarshal(data, element); err != nil {93 return nil, err94 }95 return resolvedPath, nil96}97func (loader *Loader) readURL(location *url.URL) ([]byte, error) {98 if f := loader.ReadFromURIFunc; f != nil {99 return f(loader, location)100 }101 if location.Scheme != "" && location.Host != "" {102 resp, err := http.Get(location.String())103 if err != nil {104 return nil, err105 }106 defer resp.Body.Close()107 if resp.StatusCode > 399 {108 return nil, fmt.Errorf("error loading %q: request returned status code %d", location.String(), resp.StatusCode)109 }110 return ioutil.ReadAll(resp.Body)111 }112 if location.Scheme != "" || location.Host != "" || location.RawQuery != "" {113 return nil, fmt.Errorf("unsupported URI: %q", location.String())114 }115 return ioutil.ReadFile(location.Path)116}117// LoadFromData loads a spec from a byte array118func (loader *Loader) LoadFromData(data []byte) (*T, error) {119 loader.resetVisitedPathItemRefs()120 doc := &T{}121 if err := yaml.Unmarshal(data, doc); err != nil {122 return nil, err123 }124 if err := loader.ResolveRefsIn(doc, nil); err != nil {125 return nil, err126 }127 return doc, nil128}129// LoadFromDataWithPath takes the OpenAPI document data in bytes and a path where the resolver can find referred130// elements and returns a *T with all resolved data or an error if unable to load data or resolve refs.131func (loader *Loader) LoadFromDataWithPath(data []byte, location *url.URL) (*T, error) {132 loader.resetVisitedPathItemRefs()133 return loader.loadFromDataWithPathInternal(data, location)134}135func (loader *Loader) loadFromDataWithPathInternal(data []byte, location *url.URL) (*T, error) {136 if loader.visitedDocuments == nil {137 loader.visitedDocuments = make(map[string]*T)138 }139 uri := location.String()140 if doc, ok := loader.visitedDocuments[uri]; ok {141 return doc, nil142 }143 doc := &T{}144 loader.visitedDocuments[uri] = doc145 if err := yaml.Unmarshal(data, doc); err != nil {146 return nil, err147 }148 if err := loader.ResolveRefsIn(doc, location); err != nil {149 return nil, err150 }151 return doc, nil152}153// ResolveRefsIn expands references if for instance spec was just unmarshalled154func (loader *Loader) ResolveRefsIn(doc *T, location *url.URL) (err error) {155 if loader.visitedPathItemRefs == nil {156 loader.resetVisitedPathItemRefs()157 }158 // Visit all components159 components := doc.Components160 for _, component := range components.Headers {161 if err = loader.resolveHeaderRef(doc, component, location); err != nil {162 return163 }164 }165 for _, component := range components.Parameters {166 if err = loader.resolveParameterRef(doc, component, location); err != nil {167 return168 }169 }170 for _, component := range components.RequestBodies {171 if err = loader.resolveRequestBodyRef(doc, component, location); err != nil {172 return173 }174 }175 for _, component := range components.Responses {176 if err = loader.resolveResponseRef(doc, component, location); err != nil {177 return178 }179 }180 for _, component := range components.Schemas {181 if err = loader.resolveSchemaRef(doc, component, location); err != nil {182 return183 }184 }185 for _, component := range components.SecuritySchemes {186 if err = loader.resolveSecuritySchemeRef(doc, component, location); err != nil {187 return188 }189 }190 for _, component := range components.Examples {191 if err = loader.resolveExampleRef(doc, component, location); err != nil {192 return193 }194 }195 for _, component := range components.Callbacks {196 if err = loader.resolveCallbackRef(doc, component, location); err != nil {197 return198 }199 }200 // Visit all operations201 for entrypoint, pathItem := range doc.Paths {202 if pathItem == nil {203 continue204 }205 if err = loader.resolvePathItemRef(doc, entrypoint, pathItem, location); err != nil {206 return207 }208 }209 return210}211func join(basePath *url.URL, relativePath *url.URL) (*url.URL, error) {212 if basePath == nil {213 return relativePath, nil214 }215 newPath, err := url.Parse(basePath.String())216 if err != nil {217 return nil, fmt.Errorf("cannot copy path: %q", basePath.String())218 }219 newPath.Path = path.Join(path.Dir(newPath.Path), relativePath.Path)220 return newPath, nil221}222func resolvePath(basePath *url.URL, componentPath *url.URL) (*url.URL, error) {223 if componentPath.Scheme == "" && componentPath.Host == "" {224 // support absolute paths225 if componentPath.Path[0] == '/' {226 return componentPath, nil227 }228 return join(basePath, componentPath)229 }230 return componentPath, nil231}232func isSingleRefElement(ref string) bool {233 return !strings.Contains(ref, "#")234}235func (loader *Loader) resolveComponent(236 doc *T,237 ref string,238 path *url.URL,239 resolved interface{},240) (241 componentPath *url.URL,242 err error,243) {244 if doc, ref, componentPath, err = loader.resolveRef(doc, ref, path); err != nil {245 return nil, err246 }247 parsedURL, err := url.Parse(ref)248 if err != nil {249 return nil, fmt.Errorf("cannot parse reference: %q: %v", ref, parsedURL)250 }251 fragment := parsedURL.Fragment252 if !strings.HasPrefix(fragment, "/") {253 return nil, fmt.Errorf("expected fragment prefix '#/' in URI %q", ref)254 }255 drill := func(cursor interface{}) (interface{}, error) {256 for _, pathPart := range strings.Split(fragment[1:], "/") {257 pathPart = unescapeRefString(pathPart)258 if cursor, err = drillIntoField(cursor, pathPart); err != nil {259 e := failedToResolveRefFragmentPart(ref, pathPart)260 return nil, fmt.Errorf("%s: %s", e.Error(), err.Error())261 }262 if cursor == nil {263 return nil, failedToResolveRefFragmentPart(ref, pathPart)264 }265 }266 return cursor, nil267 }268 var cursor interface{}269 if cursor, err = drill(doc); err != nil {270 if path == nil {271 return nil, err272 }273 var err2 error274 data, err2 := loader.readURL(path)275 if err2 != nil {276 return nil, err277 }278 if err2 = yaml.Unmarshal(data, &cursor); err2 != nil {279 return nil, err280 }281 if cursor, err2 = drill(cursor); err2 != nil || cursor == nil {282 return nil, err283 }284 err = nil285 }286 switch {287 case reflect.TypeOf(cursor) == reflect.TypeOf(resolved):288 reflect.ValueOf(resolved).Elem().Set(reflect.ValueOf(cursor).Elem())289 return componentPath, nil290 case reflect.TypeOf(cursor) == reflect.TypeOf(map[string]interface{}{}):291 codec := func(got, expect interface{}) error {292 enc, err := json.Marshal(got)293 if err != nil {294 return err295 }296 if err = json.Unmarshal(enc, expect); err != nil {297 return err298 }299 return nil300 }301 if err := codec(cursor, resolved); err != nil {302 return nil, fmt.Errorf("bad data in %q", ref)303 }304 return componentPath, nil305 default:306 return nil, fmt.Errorf("bad data in %q", ref)307 }308}309func drillIntoField(cursor interface{}, fieldName string) (interface{}, error) {310 // Special case due to multijson311 if s, ok := cursor.(*SchemaRef); ok && fieldName == "additionalProperties" {312 if ap := s.Value.AdditionalPropertiesAllowed; ap != nil {313 return *ap, nil314 }315 return s.Value.AdditionalProperties, nil316 }317 switch val := reflect.Indirect(reflect.ValueOf(cursor)); val.Kind() {318 case reflect.Map:319 elementValue := val.MapIndex(reflect.ValueOf(fieldName))320 if !elementValue.IsValid() {321 return nil, fmt.Errorf("map key %q not found", fieldName)322 }323 return elementValue.Interface(), nil324 case reflect.Slice:325 i, err := strconv.ParseUint(fieldName, 10, 32)326 if err != nil {327 return nil, err328 }329 index := int(i)330 if 0 > index || index >= val.Len() {331 return nil, errors.New("slice index out of bounds")332 }333 return val.Index(index).Interface(), nil334 case reflect.Struct:335 hasFields := false336 for i := 0; i < val.NumField(); i++ {337 hasFields = true338 field := val.Type().Field(i)339 tagValue := field.Tag.Get("yaml")340 yamlKey := strings.Split(tagValue, ",")[0]341 if yamlKey == "-" {342 tagValue := field.Tag.Get("multijson")343 yamlKey = strings.Split(tagValue, ",")[0]344 }345 if yamlKey == fieldName {346 return val.Field(i).Interface(), nil347 }348 }349 // if cursor is a "ref wrapper" struct (e.g. RequestBodyRef),350 if _, ok := val.Type().FieldByName("Value"); ok {351 // try digging into its Value field352 return drillIntoField(val.FieldByName("Value").Interface(), fieldName)353 }354 if hasFields {355 if ff := val.Type().Field(0); ff.PkgPath == "" && ff.Name == "ExtensionProps" {356 extensions := val.Field(0).Interface().(ExtensionProps).Extensions357 if enc, ok := extensions[fieldName]; ok {358 var dec interface{}359 if err := json.Unmarshal(enc.(json.RawMessage), &dec); err != nil {360 return nil, err361 }362 return dec, nil363 }364 }365 }366 return nil, fmt.Errorf("struct field %q not found", fieldName)367 default:368 return nil, errors.New("not a map, slice nor struct")369 }370}371func (loader *Loader) documentPathForRecursiveRef(current *url.URL, resolvedRef string) *url.URL {372 if loader.rootDir == "" {373 return current374 }375 return &url.URL{Path: path.Join(loader.rootDir, resolvedRef)}376}377func (loader *Loader) resolveRef(doc *T, ref string, path *url.URL) (*T, string, *url.URL, error) {378 if ref != "" && ref[0] == '#' {379 return doc, ref, path, nil380 }381 if err := loader.allowsExternalRefs(ref); err != nil {382 return nil, "", nil, err383 }384 parsedURL, err := url.Parse(ref)385 if err != nil {386 return nil, "", nil, fmt.Errorf("cannot parse reference: %q: %v", ref, parsedURL)387 }388 fragment := parsedURL.Fragment389 parsedURL.Fragment = ""390 var resolvedPath *url.URL391 if resolvedPath, err = resolvePath(path, parsedURL); err != nil {392 return nil, "", nil, fmt.Errorf("error resolving path: %v", err)393 }394 if doc, err = loader.loadFromURIInternal(resolvedPath); err != nil {395 return nil, "", nil, fmt.Errorf("error resolving reference %q: %v", ref, err)396 }397 return doc, "#" + fragment, resolvedPath, nil398}399func (loader *Loader) resolveHeaderRef(doc *T, component *HeaderRef, documentPath *url.URL) (err error) {400 if component != nil && component.Value != nil {401 if loader.visitedHeader == nil {402 loader.visitedHeader = make(map[*Header]struct{})403 }404 if _, ok := loader.visitedHeader[component.Value]; ok {405 return nil406 }407 loader.visitedHeader[component.Value] = struct{}{}408 }409 if component == nil {410 return errors.New("invalid header: value MUST be an object")411 }412 if ref := component.Ref; ref != "" {413 if isSingleRefElement(ref) {414 var header Header415 if documentPath, err = loader.loadSingleElementFromURI(ref, documentPath, &header); err != nil {416 return err417 }418 component.Value = &header419 } else {420 var resolved HeaderRef421 componentPath, err := loader.resolveComponent(doc, ref, documentPath, &resolved)422 if err != nil {423 return err424 }425 if err := loader.resolveHeaderRef(doc, &resolved, componentPath); err != nil {426 return err427 }428 component.Value = resolved.Value429 documentPath = loader.documentPathForRecursiveRef(documentPath, resolved.Ref)430 }431 }432 value := component.Value433 if value == nil {434 return nil435 }436 if schema := value.Schema; schema != nil {437 if err := loader.resolveSchemaRef(doc, schema, documentPath); err != nil {438 return err439 }440 }441 return nil442}443func (loader *Loader) resolveParameterRef(doc *T, component *ParameterRef, documentPath *url.URL) (err error) {444 if component != nil && component.Value != nil {445 if loader.visitedParameter == nil {446 loader.visitedParameter = make(map[*Parameter]struct{})447 }448 if _, ok := loader.visitedParameter[component.Value]; ok {449 return nil450 }451 loader.visitedParameter[component.Value] = struct{}{}452 }453 if component == nil {454 return errors.New("invalid parameter: value MUST be an object")455 }456 ref := component.Ref457 if ref != "" {458 if isSingleRefElement(ref) {459 var param Parameter460 if documentPath, err = loader.loadSingleElementFromURI(ref, documentPath, &param); err != nil {461 return err462 }463 component.Value = &param464 } else {465 var resolved ParameterRef466 componentPath, err := loader.resolveComponent(doc, ref, documentPath, &resolved)467 if err != nil {468 return err469 }470 if err := loader.resolveParameterRef(doc, &resolved, componentPath); err != nil {471 return err472 }473 component.Value = resolved.Value474 documentPath = loader.documentPathForRecursiveRef(documentPath, resolved.Ref)475 }476 }477 value := component.Value478 if value == nil {479 return nil480 }481 if value.Content != nil && value.Schema != nil {482 return errors.New("cannot contain both schema and content in a parameter")483 }484 for _, contentType := range value.Content {485 if schema := contentType.Schema; schema != nil {486 if err := loader.resolveSchemaRef(doc, schema, documentPath); err != nil {487 return err488 }489 }490 }491 if schema := value.Schema; schema != nil {492 if err := loader.resolveSchemaRef(doc, schema, documentPath); err != nil {493 return err494 }495 }496 return nil497}498func (loader *Loader) resolveRequestBodyRef(doc *T, component *RequestBodyRef, documentPath *url.URL) (err error) {499 if component != nil && component.Value != nil {500 if loader.visitedRequestBody == nil {501 loader.visitedRequestBody = make(map[*RequestBody]struct{})502 }503 if _, ok := loader.visitedRequestBody[component.Value]; ok {504 return nil505 }506 loader.visitedRequestBody[component.Value] = struct{}{}507 }508 if component == nil {509 return errors.New("invalid requestBody: value MUST be an object")510 }511 if ref := component.Ref; ref != "" {512 if isSingleRefElement(ref) {513 var requestBody RequestBody514 if documentPath, err = loader.loadSingleElementFromURI(ref, documentPath, &requestBody); err != nil {515 return err516 }517 component.Value = &requestBody518 } else {519 var resolved RequestBodyRef520 componentPath, err := loader.resolveComponent(doc, ref, documentPath, &resolved)521 if err != nil {522 return err523 }524 if err = loader.resolveRequestBodyRef(doc, &resolved, componentPath); err != nil {525 return err526 }527 component.Value = resolved.Value528 documentPath = loader.documentPathForRecursiveRef(documentPath, resolved.Ref)529 }530 }531 value := component.Value532 if value == nil {533 return nil534 }535 for _, contentType := range value.Content {536 for name, example := range contentType.Examples {537 if err := loader.resolveExampleRef(doc, example, documentPath); err != nil {538 return err539 }540 contentType.Examples[name] = example541 }542 if schema := contentType.Schema; schema != nil {543 if err := loader.resolveSchemaRef(doc, schema, documentPath); err != nil {544 return err545 }546 }547 }548 return nil549}550func (loader *Loader) resolveResponseRef(doc *T, component *ResponseRef, documentPath *url.URL) (err error) {551 if component != nil && component.Value != nil {552 if loader.visitedResponse == nil {553 loader.visitedResponse = make(map[*Response]struct{})554 }555 if _, ok := loader.visitedResponse[component.Value]; ok {556 return nil557 }558 loader.visitedResponse[component.Value] = struct{}{}559 }560 if component == nil {561 return errors.New("invalid response: value MUST be an object")562 }563 ref := component.Ref564 if ref != "" {565 if isSingleRefElement(ref) {566 var resp Response567 if documentPath, err = loader.loadSingleElementFromURI(ref, documentPath, &resp); err != nil {568 return err569 }570 component.Value = &resp571 } else {572 var resolved ResponseRef573 componentPath, err := loader.resolveComponent(doc, ref, documentPath, &resolved)574 if err != nil {575 return err576 }577 if err := loader.resolveResponseRef(doc, &resolved, componentPath); err != nil {578 return err579 }580 component.Value = resolved.Value581 documentPath = loader.documentPathForRecursiveRef(documentPath, resolved.Ref)582 }583 }584 value := component.Value585 if value == nil {586 return nil587 }588 for _, header := range value.Headers {589 if err := loader.resolveHeaderRef(doc, header, documentPath); err != nil {590 return err591 }592 }593 for _, contentType := range value.Content {594 if contentType == nil {595 continue596 }597 for name, example := range contentType.Examples {598 if err := loader.resolveExampleRef(doc, example, documentPath); err != nil {599 return err600 }601 contentType.Examples[name] = example602 }603 if schema := contentType.Schema; schema != nil {604 if err := loader.resolveSchemaRef(doc, schema, documentPath); err != nil {605 return err606 }607 contentType.Schema = schema608 }609 }610 for _, link := range value.Links {611 if err := loader.resolveLinkRef(doc, link, documentPath); err != nil {612 return err613 }614 }615 return nil616}617func (loader *Loader) resolveSchemaRef(doc *T, component *SchemaRef, documentPath *url.URL) (err error) {618 if component != nil && component.Value != nil {619 if loader.visitedSchema == nil {620 loader.visitedSchema = make(map[*Schema]struct{})621 }622 if _, ok := loader.visitedSchema[component.Value]; ok {623 return nil624 }625 loader.visitedSchema[component.Value] = struct{}{}626 }627 if component == nil {628 return errors.New("invalid schema: value MUST be an object")629 }630 ref := component.Ref631 if ref != "" {632 if isSingleRefElement(ref) {633 var schema Schema634 if documentPath, err = loader.loadSingleElementFromURI(ref, documentPath, &schema); err != nil {635 return err636 }637 component.Value = &schema638 } else {639 var resolved SchemaRef640 componentPath, err := loader.resolveComponent(doc, ref, documentPath, &resolved)641 if err != nil {642 return err643 }644 if err := loader.resolveSchemaRef(doc, &resolved, componentPath); err != nil {645 return err646 }647 component.Value = resolved.Value648 documentPath = loader.documentPathForRecursiveRef(documentPath, resolved.Ref)649 }650 }651 value := component.Value652 if value == nil {653 return nil654 }655 // ResolveRefs referred schemas656 if v := value.Items; v != nil {657 if err := loader.resolveSchemaRef(doc, v, documentPath); err != nil {658 return err659 }660 }661 for _, v := range value.Properties {662 if err := loader.resolveSchemaRef(doc, v, documentPath); err != nil {663 return err664 }665 }666 if v := value.AdditionalProperties; v != nil {667 if err := loader.resolveSchemaRef(doc, v, documentPath); err != nil {668 return err669 }670 }671 if v := value.Not; v != nil {672 if err := loader.resolveSchemaRef(doc, v, documentPath); err != nil {673 return err674 }675 }676 for _, v := range value.AllOf {677 if err := loader.resolveSchemaRef(doc, v, documentPath); err != nil {678 return err679 }680 }681 for _, v := range value.AnyOf {682 if err := loader.resolveSchemaRef(doc, v, documentPath); err != nil {683 return err684 }685 }686 for _, v := range value.OneOf {687 if err := loader.resolveSchemaRef(doc, v, documentPath); err != nil {688 return err689 }690 }691 return nil692}693func (loader *Loader) resolveSecuritySchemeRef(doc *T, component *SecuritySchemeRef, documentPath *url.URL) (err error) {694 if component != nil && component.Value != nil {695 if loader.visitedSecurityScheme == nil {696 loader.visitedSecurityScheme = make(map[*SecurityScheme]struct{})697 }698 if _, ok := loader.visitedSecurityScheme[component.Value]; ok {699 return nil700 }701 loader.visitedSecurityScheme[component.Value] = struct{}{}702 }703 if component == nil {704 return errors.New("invalid securityScheme: value MUST be an object")705 }706 if ref := component.Ref; ref != "" {707 if isSingleRefElement(ref) {708 var scheme SecurityScheme709 if _, err = loader.loadSingleElementFromURI(ref, documentPath, &scheme); err != nil {710 return err711 }712 component.Value = &scheme713 } else {714 var resolved SecuritySchemeRef715 componentPath, err := loader.resolveComponent(doc, ref, documentPath, &resolved)716 if err != nil {717 return err718 }719 if err := loader.resolveSecuritySchemeRef(doc, &resolved, componentPath); err != nil {720 return err721 }722 component.Value = resolved.Value723 _ = loader.documentPathForRecursiveRef(documentPath, resolved.Ref)724 }725 }726 return nil727}728func (loader *Loader) resolveExampleRef(doc *T, component *ExampleRef, documentPath *url.URL) (err error) {729 if component != nil && component.Value != nil {730 if loader.visitedExample == nil {731 loader.visitedExample = make(map[*Example]struct{})732 }733 if _, ok := loader.visitedExample[component.Value]; ok {734 return nil735 }736 loader.visitedExample[component.Value] = struct{}{}737 }738 if component == nil {739 return errors.New("invalid example: value MUST be an object")740 }741 if ref := component.Ref; ref != "" {742 if isSingleRefElement(ref) {743 var example Example744 if _, err = loader.loadSingleElementFromURI(ref, documentPath, &example); err != nil {745 return err746 }747 component.Value = &example748 } else {749 var resolved ExampleRef750 componentPath, err := loader.resolveComponent(doc, ref, documentPath, &resolved)751 if err != nil {752 return err753 }754 if err := loader.resolveExampleRef(doc, &resolved, componentPath); err != nil {755 return err756 }757 component.Value = resolved.Value758 _ = loader.documentPathForRecursiveRef(documentPath, resolved.Ref)759 }760 }761 return nil762}763func (loader *Loader) resolveCallbackRef(doc *T, component *CallbackRef, documentPath *url.URL) (err error) {764 if component == nil {765 return errors.New("invalid callback: value MUST be an object")766 }767 if ref := component.Ref; ref != "" {768 if isSingleRefElement(ref) {769 var resolved Callback770 if documentPath, err = loader.loadSingleElementFromURI(ref, documentPath, &resolved); err != nil {771 return err772 }773 component.Value = &resolved774 } else {775 var resolved CallbackRef776 componentPath, err := loader.resolveComponent(doc, ref, documentPath, &resolved)777 if err != nil {778 return err779 }780 if err := loader.resolveCallbackRef(doc, &resolved, componentPath); err != nil {781 return err782 }783 component.Value = resolved.Value784 documentPath = loader.documentPathForRecursiveRef(documentPath, resolved.Ref)785 }786 }787 value := component.Value788 if value == nil {789 return nil790 }791 for entrypoint, pathItem := range *value {792 entrypoint, pathItem := entrypoint, pathItem793 err = func() (err error) {794 key := "-"795 if documentPath != nil {796 key = documentPath.EscapedPath()797 }798 key += entrypoint799 if _, ok := loader.visitedPathItemRefs[key]; ok {800 return nil801 }802 loader.visitedPathItemRefs[key] = struct{}{}803 if pathItem == nil {804 return errors.New("invalid path item: value MUST be an object")805 }806 ref := pathItem.Ref807 if ref != "" {808 if isSingleRefElement(ref) {809 var p PathItem810 if documentPath, err = loader.loadSingleElementFromURI(ref, documentPath, &p); err != nil {811 return err812 }813 *pathItem = p814 } else {815 if doc, ref, documentPath, err = loader.resolveRef(doc, ref, documentPath); err != nil {816 return817 }818 rest := strings.TrimPrefix(ref, "#/components/callbacks/")819 if rest == ref {820 return fmt.Errorf(`expected prefix "#/components/callbacks/" in URI %q`, ref)821 }822 id := unescapeRefString(rest)823 definitions := doc.Components.Callbacks824 if definitions == nil {825 return failedToResolveRefFragmentPart(ref, "callbacks")826 }827 resolved := definitions[id]828 if resolved == nil {829 return failedToResolveRefFragmentPart(ref, id)830 }831 for _, p := range *resolved.Value {832 *pathItem = *p833 break834 }835 }836 }837 return loader.resolvePathItemRefContinued(doc, pathItem, documentPath)838 }()839 if err != nil {840 return err841 }842 }843 return nil844}845func (loader *Loader) resolveLinkRef(doc *T, component *LinkRef, documentPath *url.URL) (err error) {846 if component != nil && component.Value != nil {847 if loader.visitedLink == nil {848 loader.visitedLink = make(map[*Link]struct{})849 }850 if _, ok := loader.visitedLink[component.Value]; ok {851 return nil852 }853 loader.visitedLink[component.Value] = struct{}{}854 }855 if component == nil {856 return errors.New("invalid link: value MUST be an object")857 }858 if ref := component.Ref; ref != "" {859 if isSingleRefElement(ref) {860 var link Link861 if _, err = loader.loadSingleElementFromURI(ref, documentPath, &link); err != nil {862 return err863 }864 component.Value = &link865 } else {866 var resolved LinkRef867 componentPath, err := loader.resolveComponent(doc, ref, documentPath, &resolved)868 if err != nil {869 return err870 }871 if err := loader.resolveLinkRef(doc, &resolved, componentPath); err != nil {872 return err873 }874 component.Value = resolved.Value875 _ = loader.documentPathForRecursiveRef(documentPath, resolved.Ref)876 }877 }878 return nil879}880func (loader *Loader) resolvePathItemRef(doc *T, entrypoint string, pathItem *PathItem, documentPath *url.URL) (err error) {881 key := "_"882 if documentPath != nil {883 key = documentPath.EscapedPath()884 }885 key += entrypoint886 if _, ok := loader.visitedPathItemRefs[key]; ok {887 return nil888 }889 loader.visitedPathItemRefs[key] = struct{}{}890 if pathItem == nil {891 return errors.New("invalid path item: value MUST be an object")892 }893 ref := pathItem.Ref894 if ref != "" {895 if isSingleRefElement(ref) {896 var p PathItem897 if documentPath, err = loader.loadSingleElementFromURI(ref, documentPath, &p); err != nil {898 return err899 }900 *pathItem = p901 } else {902 if doc, ref, documentPath, err = loader.resolveRef(doc, ref, documentPath); err != nil {903 return904 }905 rest := strings.TrimPrefix(ref, "#/paths/")906 if rest == ref {907 return fmt.Errorf(`expected prefix "#/paths/" in URI %q`, ref)908 }909 id := unescapeRefString(rest)910 definitions := doc.Paths911 if definitions == nil {912 return failedToResolveRefFragmentPart(ref, "paths")913 }914 resolved := definitions[id]915 if resolved == nil {916 return failedToResolveRefFragmentPart(ref, id)917 }918 *pathItem = *resolved919 }920 }921 return loader.resolvePathItemRefContinued(doc, pathItem, documentPath)922}923func (loader *Loader) resolvePathItemRefContinued(doc *T, pathItem *PathItem, documentPath *url.URL) (err error) {924 for _, parameter := range pathItem.Parameters {925 if err = loader.resolveParameterRef(doc, parameter, documentPath); err != nil {926 return927 }928 }929 for _, operation := range pathItem.Operations() {930 for _, parameter := range operation.Parameters {...

Full Screen

Full Screen

swagger_loader.go

Source:swagger_loader.go Github

copy

Full Screen

...15)16func foundUnresolvedRef(ref string) error {17 return fmt.Errorf("Found unresolved ref: '%s'", ref)18}19func failedToResolveRefFragment(value string) error {20 return fmt.Errorf("Failed to resolve fragment in URI: '%s'", value)21}22func failedToResolveRefFragmentPart(value string, what string) error {23 return fmt.Errorf("Failed to resolve '%s' in fragment in URI: '%s'", what, value)24}25type SwaggerLoader struct {26 IsExternalRefsAllowed bool27 Context context.Context28 LoadSwaggerFromURIFunc func(loader *SwaggerLoader, url *url.URL) (*Swagger, error)29 visited map[interface{}]struct{}30 visitedFiles map[string]struct{}31}32func NewSwaggerLoader() *SwaggerLoader {33 return &SwaggerLoader{}34}35func (swaggerLoader *SwaggerLoader) reset() {36 swaggerLoader.visitedFiles = make(map[string]struct{})37}38func (swaggerLoader *SwaggerLoader) LoadSwaggerFromURI(location *url.URL) (*Swagger, error) {39 swaggerLoader.reset()40 return swaggerLoader.loadSwaggerFromURIInternal(location)41}42func (swaggerLoader *SwaggerLoader) loadSwaggerFromURIInternal(location *url.URL) (*Swagger, error) {43 f := swaggerLoader.LoadSwaggerFromURIFunc44 if f != nil {45 return f(swaggerLoader, location)46 }47 data, err := readURL(location)48 if err != nil {49 return nil, err50 }51 return swaggerLoader.loadSwaggerFromDataWithPathInternal(data, location)52}53// loadSingleElementFromURI read the data from ref and unmarshal to JSON to the54// passed element.55func (swaggerLoader *SwaggerLoader) loadSingleElementFromURI(ref string, rootPath *url.URL, element json.Unmarshaler) error {56 if !swaggerLoader.IsExternalRefsAllowed {57 return fmt.Errorf("encountered non-allowed external reference: '%s'", ref)58 }59 parsedURL, err := url.Parse(ref)60 if err != nil {61 return err62 }63 if parsedURL.Fragment != "" {64 return errors.New("references to files which contain more than one element definition are not supported")65 }66 resolvedPath, err := resolvePath(rootPath, parsedURL)67 if err != nil {68 return fmt.Errorf("could not resolve path: %v", err)69 }70 data, err := readURL(resolvedPath)71 if err != nil {72 return err73 }74 if err := yaml.Unmarshal(data, element); err != nil {75 return err76 }77 return nil78}79func readURL(location *url.URL) ([]byte, error) {80 if location.Scheme != "" && location.Host != "" {81 resp, err := http.Get(location.String())82 if err != nil {83 return nil, err84 }85 data, err := ioutil.ReadAll(resp.Body)86 defer resp.Body.Close()87 if err != nil {88 return nil, err89 }90 return data, nil91 }92 if location.Scheme != "" || location.Host != "" || location.RawQuery != "" {93 return nil, fmt.Errorf("Unsupported URI: '%s'", location.String())94 }95 data, err := ioutil.ReadFile(location.Path)96 if err != nil {97 return nil, err98 }99 return data, nil100}101func (swaggerLoader *SwaggerLoader) LoadSwaggerFromFile(path string) (*Swagger, error) {102 swaggerLoader.reset()103 return swaggerLoader.loadSwaggerFromFileInternal(path)104}105func (swaggerLoader *SwaggerLoader) loadSwaggerFromFileInternal(path string) (*Swagger, error) {106 f := swaggerLoader.LoadSwaggerFromURIFunc107 if f != nil {108 return f(swaggerLoader, &url.URL{109 Path: path,110 })111 }112 data, err := ioutil.ReadFile(path)113 if err != nil {114 return nil, err115 }116 return swaggerLoader.loadSwaggerFromDataWithPathInternal(data, &url.URL{117 Path: path,118 })119}120func (swaggerLoader *SwaggerLoader) LoadSwaggerFromData(data []byte) (*Swagger, error) {121 swaggerLoader.reset()122 return swaggerLoader.loadSwaggerFromDataInternal(data)123}124func (swaggerLoader *SwaggerLoader) loadSwaggerFromDataInternal(data []byte) (*Swagger, error) {125 swagger := &Swagger{}126 if err := yaml.Unmarshal(data, swagger); err != nil {127 return nil, err128 }129 return swagger, swaggerLoader.ResolveRefsIn(swagger, nil)130}131// LoadSwaggerFromDataWithPath takes the OpenApi spec data in bytes and a path where the resolver can find referred132// elements and returns a *Swagger with all resolved data or an error if unable to load data or resolve refs.133func (swaggerLoader *SwaggerLoader) LoadSwaggerFromDataWithPath(data []byte, path *url.URL) (*Swagger, error) {134 swaggerLoader.reset()135 return swaggerLoader.loadSwaggerFromDataWithPathInternal(data, path)136}137func (swaggerLoader *SwaggerLoader) loadSwaggerFromDataWithPathInternal(data []byte, path *url.URL) (*Swagger, error) {138 swagger := &Swagger{}139 if err := yaml.Unmarshal(data, swagger); err != nil {140 return nil, err141 }142 return swagger, swaggerLoader.ResolveRefsIn(swagger, path)143}144func (swaggerLoader *SwaggerLoader) ResolveRefsIn(swagger *Swagger, path *url.URL) (err error) {145 swaggerLoader.visited = make(map[interface{}]struct{})146 if swaggerLoader.visitedFiles == nil {147 swaggerLoader.visitedFiles = make(map[string]struct{})148 }149 // Visit all components150 components := swagger.Components151 for _, component := range components.Headers {152 if err = swaggerLoader.resolveHeaderRef(swagger, component, path); err != nil {153 return154 }155 }156 for _, component := range components.Parameters {157 if err = swaggerLoader.resolveParameterRef(swagger, component, path); err != nil {158 return159 }160 }161 for _, component := range components.RequestBodies {162 if err = swaggerLoader.resolveRequestBodyRef(swagger, component, path); err != nil {163 return164 }165 }166 for _, component := range components.Responses {167 if err = swaggerLoader.resolveResponseRef(swagger, component, path); err != nil {168 return169 }170 }171 for _, component := range components.Schemas {172 if err = swaggerLoader.resolveSchemaRef(swagger, component, path); err != nil {173 return174 }175 }176 for _, component := range components.SecuritySchemes {177 if err = swaggerLoader.resolveSecuritySchemeRef(swagger, component, path); err != nil {178 return179 }180 }181 for _, component := range components.Examples {182 if err = swaggerLoader.resolveExampleRef(swagger, component, path); err != nil {183 return184 }185 }186 // Visit all operations187 for entrypoint, pathItem := range swagger.Paths {188 if pathItem == nil {189 continue190 }191 if err = swaggerLoader.resolvePathItemRef(swagger, entrypoint, pathItem, path); err != nil {192 return193 }194 }195 return196}197func copyURL(basePath *url.URL) (*url.URL, error) {198 return url.Parse(basePath.String())199}200func join(basePath *url.URL, relativePath *url.URL) (*url.URL, error) {201 if basePath == nil {202 return relativePath, nil203 }204 newPath, err := copyURL(basePath)205 if err != nil {206 return nil, fmt.Errorf("Can't copy path: '%s'", basePath.String())207 }208 newPath.Path = path.Join(path.Dir(newPath.Path), relativePath.Path)209 return newPath, nil210}211func resolvePath(basePath *url.URL, componentPath *url.URL) (*url.URL, error) {212 if componentPath.Scheme == "" && componentPath.Host == "" {213 return join(basePath, componentPath)214 }215 return componentPath, nil216}217func isSingleRefElement(ref string) bool {218 return !strings.Contains(ref, "#")219}220func (swaggerLoader *SwaggerLoader) resolveComponent(swagger *Swagger, ref string, path *url.URL) (221 cursor interface{},222 componentPath *url.URL,223 err error,224) {225 if swagger, ref, componentPath, err = swaggerLoader.resolveRefSwagger(swagger, ref, path); err != nil {226 return nil, nil, err227 }228 parsedURL, err := url.Parse(ref)229 if err != nil {230 return nil, nil, fmt.Errorf("Can't parse reference: '%s': %v", ref, parsedURL)231 }232 fragment := parsedURL.Fragment233 if !strings.HasPrefix(fragment, "/") {234 err := fmt.Errorf("expected fragment prefix '#/' in URI '%s'", ref)235 return nil, nil, err236 }237 cursor = swagger238 for _, pathPart := range strings.Split(fragment[1:], "/") {239 pathPart = strings.Replace(pathPart, "~1", "/", -1)240 pathPart = strings.Replace(pathPart, "~0", "~", -1)241 if cursor, err = drillIntoSwaggerField(cursor, pathPart); err != nil {242 return nil, nil, fmt.Errorf("Failed to resolve '%s' in fragment in URI: '%s': %v", ref, pathPart, err.Error())243 }244 if cursor == nil {245 return nil, nil, failedToResolveRefFragmentPart(ref, pathPart)246 }247 }248 return cursor, componentPath, nil249}250func drillIntoSwaggerField(cursor interface{}, fieldName string) (interface{}, error) {251 switch val := reflect.Indirect(reflect.ValueOf(cursor)); val.Kind() {252 case reflect.Map:253 elementValue := val.MapIndex(reflect.ValueOf(fieldName))254 if !elementValue.IsValid() {255 return nil, fmt.Errorf("Map key not found: %v", fieldName)256 }257 return elementValue.Interface(), nil258 case reflect.Slice:259 i, err := strconv.ParseUint(fieldName, 10, 32)260 if err != nil {261 return nil, err262 }263 index := int(i)264 if index >= val.Len() {265 return nil, errors.New("slice index out of bounds")266 }267 return val.Index(index).Interface(), nil268 case reflect.Struct:269 for i := 0; i < val.NumField(); i++ {270 field := val.Type().Field(i)271 tagValue := field.Tag.Get("yaml")272 yamlKey := strings.Split(tagValue, ",")[0]273 if yamlKey == fieldName {274 return val.Field(i).Interface(), nil275 }276 }277 // if cursor if a "ref wrapper" struct (e.g. RequestBodyRef), try digging into its Value field278 _, ok := val.Type().FieldByName("Value")279 if ok {280 return drillIntoSwaggerField(val.FieldByName("Value").Interface(), fieldName) // recurse into .Value281 }282 // give up283 return nil, fmt.Errorf("Struct field not found: %v", fieldName)284 default:285 return nil, errors.New("not a map, slice nor struct")286 }287}288func (swaggerLoader *SwaggerLoader) resolveRefSwagger(swagger *Swagger, ref string, path *url.URL) (*Swagger, string, *url.URL, error) {289 componentPath := path290 if !strings.HasPrefix(ref, "#") {291 if !swaggerLoader.IsExternalRefsAllowed {292 return nil, "", nil, fmt.Errorf("Encountered non-allowed external reference: '%s'", ref)293 }294 parsedURL, err := url.Parse(ref)295 if err != nil {296 return nil, "", nil, fmt.Errorf("Can't parse reference: '%s': %v", ref, parsedURL)297 }298 fragment := parsedURL.Fragment299 parsedURL.Fragment = ""300 resolvedPath, err := resolvePath(path, parsedURL)301 if err != nil {302 return nil, "", nil, fmt.Errorf("Error while resolving path: %v", err)303 }304 if swagger, err = swaggerLoader.loadSwaggerFromURIInternal(resolvedPath); err != nil {305 return nil, "", nil, fmt.Errorf("Error while resolving reference '%s': %v", ref, err)306 }307 ref = fmt.Sprintf("#%s", fragment)308 componentPath = resolvedPath309 }310 return swagger, ref, componentPath, nil311}312func (swaggerLoader *SwaggerLoader) resolveHeaderRef(swagger *Swagger, component *HeaderRef, path *url.URL) error {313 visited := swaggerLoader.visited314 if _, isVisited := visited[component]; isVisited {315 return nil316 }317 visited[component] = struct{}{}318 const prefix = "#/components/headers/"319 if component == nil {320 return errors.New("invalid header: value MUST be a JSON object")321 }322 if ref := component.Ref; len(ref) > 0 {323 if isSingleRefElement(ref) {324 var header Header325 if err := swaggerLoader.loadSingleElementFromURI(ref, path, &header); err != nil {326 return err327 }328 component.Value = &header329 } else {330 untypedResolved, componentPath, err := swaggerLoader.resolveComponent(swagger, ref, path)331 if err != nil {332 return err333 }334 resolved, ok := untypedResolved.(*HeaderRef)335 if !ok {336 return failedToResolveRefFragment(ref)337 }338 if err := swaggerLoader.resolveHeaderRef(swagger, resolved, componentPath); err != nil {339 return err340 }341 component.Value = resolved.Value342 }343 }344 value := component.Value345 if value == nil {346 return nil347 }348 if schema := value.Schema; schema != nil {349 if err := swaggerLoader.resolveSchemaRef(swagger, schema, path); err != nil {350 return err351 }352 }353 return nil354}355func (swaggerLoader *SwaggerLoader) resolveParameterRef(swagger *Swagger, component *ParameterRef, documentPath *url.URL) error {356 visited := swaggerLoader.visited357 if _, isVisited := visited[component]; isVisited {358 return nil359 }360 visited[component] = struct{}{}361 const prefix = "#/components/parameters/"362 if component == nil {363 return errors.New("invalid parameter: value MUST be a JSON object")364 }365 ref := component.Ref366 if len(ref) > 0 {367 if isSingleRefElement(ref) {368 var param Parameter369 if err := swaggerLoader.loadSingleElementFromURI(ref, documentPath, &param); err != nil {370 return err371 }372 component.Value = &param373 } else {374 untypedResolved, componentPath, err := swaggerLoader.resolveComponent(swagger, ref, documentPath)375 if err != nil {376 return err377 }378 resolved, ok := untypedResolved.(*ParameterRef)379 if !ok {380 return failedToResolveRefFragment(ref)381 }382 if err := swaggerLoader.resolveParameterRef(swagger, resolved, componentPath); err != nil {383 return err384 }385 component.Value = resolved.Value386 }387 }388 value := component.Value389 if value == nil {390 return nil391 }392 refDocumentPath, err := referencedDocumentPath(documentPath, ref)393 if err != nil {394 return err395 }396 if value.Content != nil && value.Schema != nil {397 return errors.New("Cannot contain both schema and content in a parameter")398 }399 for _, contentType := range value.Content {400 if schema := contentType.Schema; schema != nil {401 if err := swaggerLoader.resolveSchemaRef(swagger, schema, refDocumentPath); err != nil {402 return err403 }404 }405 }406 if schema := value.Schema; schema != nil {407 if err := swaggerLoader.resolveSchemaRef(swagger, schema, refDocumentPath); err != nil {408 return err409 }410 }411 return nil412}413func (swaggerLoader *SwaggerLoader) resolveRequestBodyRef(swagger *Swagger, component *RequestBodyRef, path *url.URL) error {414 visited := swaggerLoader.visited415 if _, isVisited := visited[component]; isVisited {416 return nil417 }418 visited[component] = struct{}{}419 const prefix = "#/components/requestBodies/"420 if component == nil {421 return errors.New("invalid requestBody: value MUST be a JSON object")422 }423 if ref := component.Ref; len(ref) > 0 {424 if isSingleRefElement(ref) {425 var requestBody RequestBody426 if err := swaggerLoader.loadSingleElementFromURI(ref, path, &requestBody); err != nil {427 return err428 }429 component.Value = &requestBody430 } else {431 untypedResolved, componentPath, err := swaggerLoader.resolveComponent(swagger, ref, path)432 if err != nil {433 return err434 }435 resolved, ok := untypedResolved.(*RequestBodyRef)436 if !ok {437 return failedToResolveRefFragment(ref)438 }439 if err = swaggerLoader.resolveRequestBodyRef(swagger, resolved, componentPath); err != nil {440 return err441 }442 component.Value = resolved.Value443 }444 }445 value := component.Value446 if value == nil {447 return nil448 }449 for _, contentType := range value.Content {450 for name, example := range contentType.Examples {451 if err := swaggerLoader.resolveExampleRef(swagger, example, path); err != nil {452 return err453 }454 contentType.Examples[name] = example455 }456 if schema := contentType.Schema; schema != nil {457 if err := swaggerLoader.resolveSchemaRef(swagger, schema, path); err != nil {458 return err459 }460 }461 }462 return nil463}464func (swaggerLoader *SwaggerLoader) resolveResponseRef(swagger *Swagger, component *ResponseRef, documentPath *url.URL) error {465 visited := swaggerLoader.visited466 if _, isVisited := visited[component]; isVisited {467 return nil468 }469 visited[component] = struct{}{}470 const prefix = "#/components/responses/"471 if component == nil {472 return errors.New("invalid response: value MUST be a JSON object")473 }474 ref := component.Ref475 if len(ref) > 0 {476 if isSingleRefElement(ref) {477 var resp Response478 if err := swaggerLoader.loadSingleElementFromURI(ref, documentPath, &resp); err != nil {479 return err480 }481 component.Value = &resp482 } else {483 untypedResolved, componentPath, err := swaggerLoader.resolveComponent(swagger, ref, documentPath)484 if err != nil {485 return err486 }487 resolved, ok := untypedResolved.(*ResponseRef)488 if !ok {489 return failedToResolveRefFragment(ref)490 }491 if err := swaggerLoader.resolveResponseRef(swagger, resolved, componentPath); err != nil {492 return err493 }494 component.Value = resolved.Value495 }496 }497 refDocumentPath, err := referencedDocumentPath(documentPath, ref)498 if err != nil {499 return err500 }501 value := component.Value502 if value == nil {503 return nil504 }505 for _, header := range value.Headers {506 if err := swaggerLoader.resolveHeaderRef(swagger, header, refDocumentPath); err != nil {507 return err508 }509 }510 for _, contentType := range value.Content {511 if contentType == nil {512 continue513 }514 for name, example := range contentType.Examples {515 if err := swaggerLoader.resolveExampleRef(swagger, example, refDocumentPath); err != nil {516 return err517 }518 contentType.Examples[name] = example519 }520 if schema := contentType.Schema; schema != nil {521 if err := swaggerLoader.resolveSchemaRef(swagger, schema, refDocumentPath); err != nil {522 return err523 }524 contentType.Schema = schema525 }526 }527 for _, link := range value.Links {528 if err := swaggerLoader.resolveLinkRef(swagger, link, refDocumentPath); err != nil {529 return err530 }531 }532 return nil533}534func (swaggerLoader *SwaggerLoader) resolveSchemaRef(swagger *Swagger, component *SchemaRef, documentPath *url.URL) error {535 visited := swaggerLoader.visited536 if _, isVisited := visited[component]; isVisited {537 return nil538 }539 visited[component] = struct{}{}540 const prefix = "#/components/schemas/"541 if component == nil {542 return errors.New("invalid schema: value MUST be a JSON object")543 }544 ref := component.Ref545 if len(ref) > 0 {546 if isSingleRefElement(ref) {547 var schema Schema548 if err := swaggerLoader.loadSingleElementFromURI(ref, documentPath, &schema); err != nil {549 return err550 }551 component.Value = &schema552 } else {553 untypedResolved, componentPath, err := swaggerLoader.resolveComponent(swagger, ref, documentPath)554 if err != nil {555 return err556 }557 resolved, ok := untypedResolved.(*SchemaRef)558 if !ok {559 return failedToResolveRefFragment(ref)560 }561 if err := swaggerLoader.resolveSchemaRef(swagger, resolved, componentPath); err != nil {562 return err563 }564 component.Value = resolved.Value565 }566 }567 refDocumentPath, err := referencedDocumentPath(documentPath, ref)568 if err != nil {569 return err570 }571 value := component.Value572 if value == nil {573 return nil574 }575 // ResolveRefs referred schemas576 if v := value.Items; v != nil {577 if err := swaggerLoader.resolveSchemaRef(swagger, v, refDocumentPath); err != nil {578 return err579 }580 }581 for _, v := range value.Properties {582 if err := swaggerLoader.resolveSchemaRef(swagger, v, refDocumentPath); err != nil {583 return err584 }585 }586 if v := value.AdditionalProperties; v != nil {587 if err := swaggerLoader.resolveSchemaRef(swagger, v, refDocumentPath); err != nil {588 return err589 }590 }591 if v := value.Not; v != nil {592 if err := swaggerLoader.resolveSchemaRef(swagger, v, refDocumentPath); err != nil {593 return err594 }595 }596 for _, v := range value.AllOf {597 if err := swaggerLoader.resolveSchemaRef(swagger, v, refDocumentPath); err != nil {598 return err599 }600 }601 for _, v := range value.AnyOf {602 if err := swaggerLoader.resolveSchemaRef(swagger, v, refDocumentPath); err != nil {603 return err604 }605 }606 for _, v := range value.OneOf {607 if err := swaggerLoader.resolveSchemaRef(swagger, v, refDocumentPath); err != nil {608 return err609 }610 }611 return nil612}613func (swaggerLoader *SwaggerLoader) resolveSecuritySchemeRef(swagger *Swagger, component *SecuritySchemeRef, path *url.URL) error {614 visited := swaggerLoader.visited615 if _, isVisited := visited[component]; isVisited {616 return nil617 }618 visited[component] = struct{}{}619 const prefix = "#/components/securitySchemes/"620 if component == nil {621 return errors.New("invalid securityScheme: value MUST be a JSON object")622 }623 if ref := component.Ref; len(ref) > 0 {624 if isSingleRefElement(ref) {625 var scheme SecurityScheme626 if err := swaggerLoader.loadSingleElementFromURI(ref, path, &scheme); err != nil {627 return err628 }629 component.Value = &scheme630 } else {631 untypedResolved, componentPath, err := swaggerLoader.resolveComponent(swagger, ref, path)632 if err != nil {633 return err634 }635 resolved, ok := untypedResolved.(*SecuritySchemeRef)636 if !ok {637 return failedToResolveRefFragment(ref)638 }639 if err := swaggerLoader.resolveSecuritySchemeRef(swagger, resolved, componentPath); err != nil {640 return err641 }642 component.Value = resolved.Value643 }644 }645 return nil646}647func (swaggerLoader *SwaggerLoader) resolveExampleRef(swagger *Swagger, component *ExampleRef, path *url.URL) error {648 visited := swaggerLoader.visited649 if _, isVisited := visited[component]; isVisited {650 return nil651 }652 visited[component] = struct{}{}653 const prefix = "#/components/examples/"654 if component == nil {655 return errors.New("invalid example: value MUST be a JSON object")656 }657 if ref := component.Ref; len(ref) > 0 {658 if isSingleRefElement(ref) {659 var example Example660 if err := swaggerLoader.loadSingleElementFromURI(ref, path, &example); err != nil {661 return err662 }663 component.Value = &example664 } else {665 untypedResolved, componentPath, err := swaggerLoader.resolveComponent(swagger, ref, path)666 if err != nil {667 return err668 }669 resolved, ok := untypedResolved.(*ExampleRef)670 if !ok {671 return failedToResolveRefFragment(ref)672 }673 if err := swaggerLoader.resolveExampleRef(swagger, resolved, componentPath); err != nil {674 return err675 }676 component.Value = resolved.Value677 }678 }679 return nil680}681func (swaggerLoader *SwaggerLoader) resolveLinkRef(swagger *Swagger, component *LinkRef, path *url.URL) error {682 visited := swaggerLoader.visited683 if _, isVisited := visited[component]; isVisited {684 return nil685 }686 visited[component] = struct{}{}687 const prefix = "#/components/links/"688 if component == nil {689 return errors.New("invalid link: value MUST be a JSON object")690 }691 if ref := component.Ref; len(ref) > 0 {692 if isSingleRefElement(ref) {693 var link Link694 if err := swaggerLoader.loadSingleElementFromURI(ref, path, &link); err != nil {695 return err696 }697 component.Value = &link698 } else {699 untypedResolved, componentPath, err := swaggerLoader.resolveComponent(swagger, ref, path)700 if err != nil {701 return err702 }703 resolved, ok := untypedResolved.(*LinkRef)704 if !ok {705 return failedToResolveRefFragment(ref)706 }707 if err := swaggerLoader.resolveLinkRef(swagger, resolved, componentPath); err != nil {708 return err709 }710 component.Value = resolved.Value711 }712 }713 return nil714}715func (swaggerLoader *SwaggerLoader) resolvePathItemRef(swagger *Swagger, entrypoint string, pathItem *PathItem, documentPath *url.URL) (err error) {716 visited := swaggerLoader.visitedFiles717 key := "_"718 if documentPath != nil {719 key = documentPath.EscapedPath()720 }721 key += entrypoint722 if _, isVisited := visited[key]; isVisited {723 return nil724 }725 visited[key] = struct{}{}726 const prefix = "#/paths/"727 if pathItem == nil {728 return errors.New("invalid path item: value MUST be a JSON object")729 }730 ref := pathItem.Ref731 if ref != "" {732 if isSingleRefElement(ref) {733 var p PathItem734 if err := swaggerLoader.loadSingleElementFromURI(ref, documentPath, &p); err != nil {735 return err736 }737 *pathItem = p738 } else {739 if swagger, ref, documentPath, err = swaggerLoader.resolveRefSwagger(swagger, ref, documentPath); err != nil {740 return741 }742 if !strings.HasPrefix(ref, prefix) {743 err = fmt.Errorf("expected prefix '%s' in URI '%s'", prefix, ref)744 return745 }746 id := unescapeRefString(ref[len(prefix):])747 definitions := swagger.Paths748 if definitions == nil {749 return failedToResolveRefFragmentPart(ref, "paths")750 }751 resolved := definitions[id]752 if resolved == nil {753 return failedToResolveRefFragmentPart(ref, id)754 }755 *pathItem = *resolved756 }757 }758 refDocumentPath, err := referencedDocumentPath(documentPath, ref)759 if err != nil {760 return err761 }762 for _, parameter := range pathItem.Parameters {763 if err = swaggerLoader.resolveParameterRef(swagger, parameter, refDocumentPath); err != nil {764 return765 }766 }767 for _, operation := range pathItem.Operations() {...

Full Screen

Full Screen

Resolve

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 loader := stdlib.NewLoader()4 value, err := loader.Resolve("math")5 if err != nil {6 fmt.Println(err)7 }8 fmt.Println(value)9}10{math 0x55b7c3b8f8f0}11import (12func main() {13 loader := stdlib.NewLoader()14 value, err := loader.Resolve("math")15 if err != nil {16 fmt.Println(err)17 }18 fmt.Println(value)19}20{math 0x55b7c3b8f8f0}21import (22func main() {23 loader := stdlib.NewLoader()24 value, err := loader.Resolve("math")25 if err != nil {26 fmt.Println(err)27 }28 fmt.Println(value)29}30{math 0x55b7c3b8f8f0}31import (32func main() {33 loader := stdlib.NewLoader()34 value, err := loader.Resolve("math")35 if err != nil {36 fmt.Println(err)37 }38 fmt.Println(value)39}40{math 0x55b7c3b8f8f0}41import (42func main() {

Full Screen

Full Screen

Resolve

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello World!")4 t := reflect.TypeOf(3)5 fmt.Println(t.String())6 fmt.Println(t)7}8import (9func main() {10 fmt.Println("Hello World!")11 t := reflect.TypeOf(3)12 fmt.Println(t.String())13 fmt.Println(t)14}15gcc (Ubuntu 5.4.0-6ubuntu1~16.04.10) 5.4.0 2016060916This is free software; see the source for copying conditions. There is NO

Full Screen

Full Screen

Resolve

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 loader := NewLoader()4 path, err := loader.Resolve("1.go")5 if err != nil {6 fmt.Println(err)7 }8 fmt.Println(path)9 fmt.Println(loader.WorkingDir())10}11type Loader struct {12}13func NewLoader() *Loader {14 workingDir, err := filepath.Abs(filepath.Dir("."))15 if err != nil {16 }17 loader := &Loader{18 }19}20func (l *Loader) Resolve(file string) (string, error) {21 absPath, err := filepath.Abs(file)22 if err != nil {23 }24 if !l.fileExists(absPath) {25 absPath = filepath.Join(l.workingDir, file)26 if !l.fileExists(absPath) {27 return "", fmt.Errorf("File %s does not exist", file)28 }29 }30}31func (l *Loader) WorkingDir() string {32}33func (l *Loader) fileExists(path string) bool {34 if _, err := filepath.Abs(path); err != nil {35 }36}

Full Screen

Full Screen

Resolve

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 wd, err := os.Getwd()4 if err != nil {5 fmt.Println(err)6 }7 fmt.Println(wd)8 absWd, err := filepath.Abs(wd)9 if err != nil {10 fmt.Println(err)11 }12 fmt.Println(absWd)13 resolvedPath := filepath.Join(absWd, "2.go")14 fmt.Println(resolvedPath)15}

Full Screen

Full Screen

Resolve

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Enter the URL:")4 fmt.Scan(&input)5 _, err := url.ParseRequestURI(input)6 if err != nil {7 fmt.Println("Invalid URL")8 os.Exit(1)9 }10 baseURL := getBaseURL(input)11 loader := NewLoader(baseURL)12 loader.Resolve(input)13 resolvedURL := loader.ResolvedURL()14 fileName := getFileName(resolvedURL)15 content, err := getContent(resolvedURL)16 if err != nil {17 fmt.Println("Unable to get the content")18 os.Exit(1)19 }20 file, err := os.Create(fileName)21 if err != nil {22 fmt.Println("Unable to create the file")23 os.Exit(1)24 }25 _, err = file.WriteString(content)26 if err != nil {27 fmt.Println("Unable to write to the file")28 os.Exit(1)29 }30 err = file.Close()31 if err != nil {32 fmt.Println("Unable to close the file")33 os.Exit(1)34 }35 workingDir, err := os.Getwd()36 if err != nil {37 fmt.Println("Unable to get the current working directory")38 os.Exit(1)39 }40 filePath := filepath.Join(workingDir, fileName)41 fmt.Println("File downloaded at:", filePath)42}43func getBaseURL(input string) string {44 u, err := url.Parse(input)45 if err != nil {46 log.Fatal(err)47 }48}49func getFileName(resolvedURL string) string {50 u, err := url.Parse(resolvedURL)51 if err != nil {52 log.Fatal(err)53 }

Full Screen

Full Screen

Resolve

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 l := loader.New()4 fmt.Println(l.Resolve("github.com"))5}6import (7type Loader struct {8}9func New() *Loader {10 return &Loader{}11}12func (l *Loader) Resolve(host string) string {13 return fmt.Sprintf("Resolved: %s", host)14}

Full Screen

Full Screen

Resolve

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 loader := runtime.Loader{}4 loader.Init()5 loader.Load("2.go")6 fmt.Println(loader.Resolve("main"))7}8func main() {9 println("hello")10}11func main() {12 println("world")13}14func main() {15 println("again")16}17func main() {18 println("again")19}20func main() {21 println("again")22}23func main() {24 println("again")25}26func main() {27 println("again")28}29func main() {30 println("again")31}32func main() {33 println("again")34}35func main() {36 println("again")37}38func main() {39 println("again")40}41func main() {42 println("again")43}44func main() {45 println("again")46}47func main() {48 println("again")49}50func main() {51 println("again")52}53func main() {54 println("again")55}56func main() {57 println("again")58}59func main() {60 println("again")61}62func main() {63 println("again")64}65func main() {66 println("again")67}68func main() {69 println("again")70}71func main() {72 println("again")73}74func main() {75 println("again")76}

Full Screen

Full Screen

Resolve

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 path, err := filepath.Abs(os.Args[0])4 if err != nil {5 fmt.Println(err)6 }7 fmt.Println(path)8}9import (10func main() {11 path, err := os.Getwd()12 if err != nil {13 fmt.Println(err)14 }15 fmt.Println(path)16}17import (18func main() {19 path, err := filepath.Abs(filepath.Dir(os.Args[0]))20 if err != nil {21 fmt.Println(err)22 }23 fmt.Println(path)24}25import (26func main() {27 path, err := filepath.Abs(filepath.Dir(os.Args[0]))28 if err != nil {29 fmt.Println(err)30 }31 fmt.Println(path)32}33import (34func main() {35 path, err := filepath.Abs(filepath.Dir(os.Args[0]))36 if err != nil {37 fmt.Println(err)38 }39 fmt.Println(path)40}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful