Skip to content

Commit

Permalink
feat: create interfaces and implementations for new services and comm…
Browse files Browse the repository at this point in the history
…ands

- Add a new file `adapterx.go` in the `pkg/adapterx` directory
- Define interfaces for `Service` and `Restful` in `adapterx.go`
- Implement methods for `Service` and `Restful` interfaces in `adapterx.go`
- Add a new file `cmdx.go` in the `pkg/cmdx` directory
- Define a `ServiceCmd` struct in `cmdx.go`
- Implement methods for creating a new service command in `cmdx.go`

Signed-off-by: Sean Zheng <[email protected]>
  • Loading branch information
blackhorseya committed Jul 26, 2024
1 parent a2ab07a commit 7d0129e
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
25 changes: 25 additions & 0 deletions pkg/adapterx/adapterx.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package adapterx

import (
"github.com/gin-gonic/gin"
)

// Service is the interface that wraps the basic Serve method.
type Service interface {
// Start a service asynchronously.
Start() error

// AwaitSignal waits for a signal to shut down the service.
AwaitSignal() error
}

// Restful is the interface that wraps the restful api method.
type Restful interface {
Service

// InitRouting init the routing of restful api.
InitRouting() error

// GetRouter returns the router of restful api.
GetRouter() *gin.Engine
}
48 changes: 48 additions & 0 deletions pkg/cmdx/cmdx.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package cmdx

import (
"os"
"os/signal"
"syscall"

"github.com/blackhorseya/ryze/pkg/adapterx"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)

// ServiceCmd represents the service command.
type ServiceCmd struct {
Use string
Short string
GetService func(v *viper.Viper) (adapterx.Restful, error)
}

// NewServiceCmd creates a new service command.
func NewServiceCmd(use string, short string, svc func(v *viper.Viper) (adapterx.Restful, error)) *cobra.Command {
return (&ServiceCmd{Use: use, Short: short, GetService: svc}).NewCmd()
}

// NewCmd creates a new service command.
func (c *ServiceCmd) NewCmd() *cobra.Command {
return &cobra.Command{
Use: c.Use,
Short: c.Short,
Run: func(cmd *cobra.Command, args []string) {
v := viper.New()

service, err := c.GetService(v)
cobra.CheckErr(err)

err = service.Start()
cobra.CheckErr(err)

signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, syscall.SIGTERM, syscall.SIGINT)

<-signalChan

err = service.AwaitSignal()
cobra.CheckErr(err)
},
}
}

0 comments on commit 7d0129e

Please sign in to comment.