Skip to content

Commit

Permalink
Create save_json.go
Browse files Browse the repository at this point in the history
  • Loading branch information
MarkRosemaker committed Nov 20, 2024
1 parent fceb538 commit c1c14b2
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions save_json.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package openapi

import (
"fmt"
"io"
"os"
"path/filepath"

_json "github.com/MarkRosemaker/openapi/internal/json"
"github.com/go-json-experiment/json"
)

func (d Document) WriteJSON(w io.Writer) error {
return json.MarshalWrite(w, d, _json.Options)
}

func (d *Document) ToJSON() ([]byte, error) {
return json.Marshal(d, _json.Options)
}

func (d *Document) WriteToFile(path string) error {
switch filepath.Ext(path) {
case ".json": // ok
default:
return fmt.Errorf("unsupported file extension: %s", filepath.Ext(path))
}

// create the underlying directories if they don't exist
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}

f, err := os.Create(path)
if err != nil {
return err
}
defer f.Close()

return d.WriteJSON(f)
}

0 comments on commit c1c14b2

Please sign in to comment.