📜  load.Embedded go open-api (1)

📅  最后修改于: 2023-12-03 15:02:46.076000             🧑  作者: Mango

Load.Embedded Go Open-API介绍

Load.Embedded是一个用于加载Open-API的Go语言库。它可以帮助开发者方便地从Open-API中获取数据,并将其转换为Go struct或JSON。

安装

要安装Load.Embedded,请使用以下命令:

go get github.com/loadembedded/go-openapi
加载Open-API定义

使用Load.Embedded加载Open-API定义非常简单。只需调用以下函数:

func LoadFromFile(specfile string) (*loads.Document, error)

这将从指定的文件中加载Open-API定义,并返回一个loads.Document对象,该对象包含已加载的API定义。如果加载失败,则会返回一个错误。

package main

import (
	"fmt"

	"github.com/loadembedded/go-openapi/loads"
)

func main() {
	doc, err := loads.LoadFromFile("swagger.json")
	if err != nil {
		fmt.Printf("Error loading API: %s\n", err)
		return
	}

	// Do something with the document...
	fmt.Printf("API loaded: %v\n", doc)
}
将API定义转换为Go结构体

一旦加载了Open-API文档,就可以使用Load.Embedded将其转换为Go结构体。要转换,请使用以下代码:

func GetSwagger(doc *loads.Document) (*openapi3.Swagger, error)
package main

import (
	"fmt"

	"github.com/getkin/kin-openapi/openapi3"
	"github.com/loadembedded/go-openapi/loads"
)

func main() {
	doc, err := loads.LoadFromFile("swagger.json")
	if err != nil {
		fmt.Printf("Error loading API: %s\n", err)
		return
	}

	swagger, err := doc.GetSwagger()
	if err != nil {
		fmt.Printf("Error loading API: %s\n", err)
		return
	}

	// Do something with the swagger definition...
	fmt.Printf("API loaded: %v\n", swagger)

	// Convert swagger definition to Go struct
	var swaggerStruct struct {
		Info    struct{ Title, Version string }
		OpenAPI string
	}

	swaggerStruct.Info.Title = swagger.Info.Title
	swaggerStruct.Info.Version = swagger.Info.Version
	swaggerStruct.OpenAPI = swagger.OpenAPI

	fmt.Printf("%+v\n", swaggerStruct)
}
将API转换为JSON

除了将API定义转换为Go结构体之外,您还可以将其转换为JSON。要将API定义转换为JSON,请使用以下代码:

func (s *Swagger) MarshalJSON() ([]byte, error)
package main

import (
	"encoding/json"
	"fmt"

	"github.com/getkin/kin-openapi/openapi3"
	"github.com/loadembedded/go-openapi/loads"
)

func main() {
	doc, err := loads.LoadFromFile("swagger.json")
	if err != nil {
		fmt.Printf("Error loading API: %s\n", err)
		return
	}

	swagger, err := doc.GetSwagger()
	if err != nil {
		fmt.Printf("Error loading API: %s\n", err)
		return
	}

	jsonBytes, err := swagger.MarshalJSON()
	if err != nil {
		fmt.Printf("Error marshalling API: %s\n", err)
		return
	}

	fmt.Printf("JSON: %s\n", string(jsonBytes))
}
贡献

如果您希望参与开发Load.Embedded或报告问题,请访问GitHub存储库