feat: use cobra to run the app

This commit is contained in:
Muyao CHEN
2024-10-01 13:37:31 +02:00
parent e13c4a9380
commit 8ae94d19a6
4 changed files with 110 additions and 17 deletions

View File

@ -0,0 +1,74 @@
// MIT License
//
// Copyright (c) 2024 vinchent <vinchent@vinchent.xyz>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package howmuch
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"github.com/spf13/cobra"
)
func errArgsForNoArgCommand(cmd string, args string) error {
return fmt.Errorf("%q does not take any argument, got %q", cmd, args)
}
// NewHowMuchCommand creates the root command.
func NewHowMuchCommand() *cobra.Command {
rootCmd := &cobra.Command{
Use: "howmuch",
Short: "howmuch is a expense-sharing application",
Long: `howmuch is a expense-sharing application that can help friends
to share their expense of an event or a trip`,
RunE: func(cmd *cobra.Command, args []string) error {
return run()
},
Args: func(cmd *cobra.Command, args []string) error {
for _, args := range args {
if len(args) > 0 {
return errArgsForNoArgCommand(cmd.CommandPath(), args)
}
}
return nil
},
SilenceUsage: true,
}
return rootCmd
}
func run() error {
fmt.Println("How much do I owe you?")
r := gin.Default()
r.GET("/", func(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{
"message": "how much?",
})
})
r.Run(":8080")
return nil
}