made a script to convert swagger to a openapi document

This commit is contained in:
James Tombleson 2024-07-17 22:01:58 -07:00
parent 27ead1c68a
commit fa1e762f51
3 changed files with 101 additions and 0 deletions

View File

@ -0,0 +1,17 @@
package main
import (
"fmt"
"os"
"git.jamestombleson.com/jtom38/newsbot-api/tools/swaggertoopenapi/src"
)
func main() {
err := src.ConvertToOpenApi("docs/swagger.json", "docs/openapi.json", true)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}

View File

@ -0,0 +1,70 @@
package src
import (
"bytes"
"fmt"
"io"
"log"
"net/http"
"os"
)
const (
ApplicationJson = "application/json"
)
func ConvertToOpenApi(filePath, outputPath string, force bool) error {
// check if the file already exists
exists, err := os.Stat(outputPath)
if exists != nil {
// if force was given, attempt to remove it
if force {
err = os.Remove(outputPath)
if err != nil {
return err
}
} else {
return fmt.Errorf("'%s' already exists and force was not approved", outputPath)
}
}
log.Printf("Reading '%s'", filePath)
content, err := os.ReadFile(filePath)
if err != nil {
return err
}
client := http.Client{}
req, err := http.NewRequest(http.MethodPost, "https://converter.swagger.io/api/convert", bytes.NewReader(content))
if err != nil {
return err
}
req.Header.Add("Accept", ApplicationJson)
req.Header.Add("Content-Type", ApplicationJson)
log.Println("Converting to OpenAPI spec")
resp, err := client.Do(req)
if err != nil {
return err
}
log.Println("Reading the response")
respContent, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
log.Println("Writing converted data to openapi.json")
writer, err := os.Create(outputPath)
if err != nil {
return err
}
defer writer.Close()
_, err = writer.Write(respContent)
if err != nil {
return err
}
return nil
}

View File

@ -0,0 +1,14 @@
package src_test
import (
"testing"
"git.jamestombleson.com/jtom38/newsbot-api/tools/swaggerToOpenapi/src"
)
func TestConvertOnline(t *testing.T) {
err := src.ConvertToOpenApi("../../docs/swagger.json", "../../docs/openapi.json", true)
if err != nil {
t.FailNow()
}
}