CLI Server CRUD

This commit is contained in:
2023-12-10 12:30:34 +08:00
parent 9aeaf0b1e2
commit 1941fd0edb
11 changed files with 197 additions and 4 deletions

View File

@ -0,0 +1,88 @@
package conn
import (
"encoding/json"
"fmt"
"github.com/rs/zerolog/log"
"github.com/samber/lo"
"github.com/spf13/viper"
"github.com/urfave/cli/v2"
)
var CliCommands = []*cli.Command{
{
Name: "list",
Aliases: []string{"ls"},
Description: "List all connected remote server",
Action: func(ctx *cli.Context) error {
var servers []CliConnection
raw, _ := json.Marshal(viper.Get("servers"))
_ = json.Unmarshal(raw, &servers)
log.Info().Msgf("There are %d server(s) connected in total.", len(servers))
for idx, server := range servers {
log.Info().Msgf("%d. %s", idx+1, server.Url)
}
return nil
},
},
{
Name: "connect",
Aliases: []string{"add"},
Description: "Connect and save configuration of remote server",
ArgsUsage: "<server url> <credential>",
Action: func(ctx *cli.Context) error {
if ctx.Args().Len() < 2 {
return fmt.Errorf("must have more two arguments: <server url> <credential>")
}
c := CliConnection{
Url: ctx.Args().Get(0),
Credential: ctx.Args().Get(1),
}
if err := c.GetConnectivity(); err != nil {
return fmt.Errorf("couldn't connect server: %s", err.Error())
} else {
var servers []CliConnection
raw, _ := json.Marshal(viper.Get("servers"))
_ = json.Unmarshal(raw, &servers)
viper.Set("servers", append(servers, c))
if err := viper.WriteConfig(); err != nil {
return err
} else {
log.Info().Msg("Successfully connected a new remote server, enter \"rds ls\" to get more info.")
return nil
}
}
},
},
{
Name: "disconnect",
Aliases: []string{"remove"},
Description: "Remove a remote server configuration",
ArgsUsage: "<server url>",
Action: func(ctx *cli.Context) error {
if ctx.Args().Len() < 1 {
return fmt.Errorf("must have more one arguments: <server url>")
}
var servers []CliConnection
raw, _ := json.Marshal(viper.Get("servers"))
_ = json.Unmarshal(raw, &servers)
viper.Set("servers", lo.Filter(servers, func(item CliConnection, idx int) bool {
return item.Url != ctx.Args().Get(0)
}))
if err := viper.WriteConfig(); err != nil {
return err
} else {
log.Info().Msg("Successfully disconnected a remote server, enter \"rds ls\" to get more info.")
return nil
}
},
},
}

View File

@ -0,0 +1,25 @@
package conn
import (
"fmt"
"github.com/gofiber/fiber/v2"
)
type CliConnection struct {
Url string `json:"url"`
Credential string `json:"credential"`
}
func (v CliConnection) GetConnectivity() error {
client := fiber.Get(v.Url + "/cgi/connectivity")
client.BasicAuth("RoadSign CLI", v.Credential)
if status, _, err := client.String(); len(err) > 0 {
return fmt.Errorf("couldn't connect to server: %q", err)
} else if status != 200 {
return fmt.Errorf("server rejected request, may cause by invalid credential")
}
return nil
}

46
pkg/cmd/cli/main.go Normal file
View File

@ -0,0 +1,46 @@
package main
import (
"os"
roadsign "code.smartsheep.studio/goatworks/roadsign/pkg"
"code.smartsheep.studio/goatworks/roadsign/pkg/cmd/cli/conn"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/spf13/viper"
"github.com/urfave/cli/v2"
)
func init() {
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stdout})
}
func main() {
// Configure settings
viper.AddConfigPath("$HOME")
viper.SetConfigName(".roadsignrc")
viper.SetConfigType("yaml")
// Load settings
if err := viper.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
viper.SafeWriteConfig()
viper.ReadInConfig()
} else {
log.Panic().Err(err).Msg("An error occurred when loading settings.")
}
}
// Configure CLI
app := &cli.App{
Name: "RoadSign CLI",
Version: roadsign.AppVersion,
Commands: append([]*cli.Command{}, conn.CliCommands...),
}
// Run CLI
if err := app.Run(os.Args); err != nil {
log.Fatal().Err(err).Msg("An error occurred when running cli.")
}
}