Generate client code based on the Swagger > OpenApi document #13
17
tools/swaggertoopenapi/main.go
Normal file
17
tools/swaggertoopenapi/main.go
Normal 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)
|
||||
}
|
||||
}
|
70
tools/swaggertoopenapi/src/online.go
Normal file
70
tools/swaggertoopenapi/src/online.go
Normal 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
|
||||
}
|
14
tools/swaggertoopenapi/src/online_test.go
Normal file
14
tools/swaggertoopenapi/src/online_test.go
Normal 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()
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user