Skip to content

Commit 998e7a6

Browse files
committed
feat(cli): Add root and serve commands
1 parent f2edc5c commit 998e7a6

File tree

3 files changed

+88
-0
lines changed

3 files changed

+88
-0
lines changed

cmd/root.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package cmd
2+
3+
import (
4+
"fmt"
5+
"os"
6+
7+
"github.com/spf13/cobra"
8+
)
9+
10+
var rootCmd = &cobra.Command{
11+
Use: "openapi-cli",
12+
Short: "A CLI for OpenAPI operations",
13+
Long: `A Command Line Interface (CLI) tool for serving, validating, and linting OpenAPI specifications.`,
14+
}
15+
16+
func init() {
17+
rootCmd.AddCommand(serveCmd)
18+
}
19+
20+
func Execute() {
21+
err := rootCmd.Execute()
22+
23+
if err != nil {
24+
fmt.Println(err)
25+
os.Exit(1)
26+
}
27+
}

cmd/serve.go

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package cmd
2+
3+
import (
4+
"fmt"
5+
"log"
6+
"net/http"
7+
"os"
8+
9+
"github.com/flowchartsman/swaggerui"
10+
"github.com/spf13/cobra"
11+
)
12+
13+
var serveCmd = &cobra.Command{
14+
Use: "serve",
15+
Short: "Serve the OpenAPI file",
16+
Long: `Starts a server to serve the OpenAPI file.`,
17+
Run: CommandServe,
18+
}
19+
20+
func init() {
21+
serveCmd.Flags().String("file", "./openapi.json", "The OpenAPI file to serve")
22+
}
23+
24+
func ReadOpenAPIFile(filePath string) ([]byte, error) {
25+
// Read the OpenAPI file
26+
// OpenAPI Specification files are in JSON or YAML format
27+
data, err := os.ReadFile(filePath)
28+
29+
if err != nil {
30+
fmt.Println("Error reading file:", err)
31+
32+
return nil, err
33+
}
34+
35+
return data, nil
36+
}
37+
38+
func CommandServe(cmd *cobra.Command, args []string) {
39+
filePath, err := cmd.Flags().GetString("file")
40+
41+
if err != nil {
42+
fmt.Println("Error reading file flag:", err)
43+
return
44+
}
45+
46+
content, err := ReadOpenAPIFile(filePath)
47+
fmt.Println(string(content))
48+
49+
http.Handle("/openapi/", http.StripPrefix("/openapi", swaggerui.Handler(content)))
50+
log.Println("serving on :8080")
51+
log.Fatal(http.ListenAndServe(":8080", nil))
52+
}

main.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package main
2+
3+
import (
4+
"github.com/mertssmnoglu/openapi-cli/cmd"
5+
)
6+
7+
func main() {
8+
cmd.Execute()
9+
}

0 commit comments

Comments
 (0)