Skip to content

Commit

Permalink
Simplified again ...
Browse files Browse the repository at this point in the history
  • Loading branch information
oversize committed May 21, 2024
1 parent a6d69b4 commit 258af80
Show file tree
Hide file tree
Showing 10 changed files with 230 additions and 184 deletions.
41 changes: 26 additions & 15 deletions cmd/bursa/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,24 +15,35 @@
package main

import (
"fmt"
"log/slog"
"os"

"github.com/blinklabs-io/bursa/internal/api"
"github.com/blinklabs-io/bursa/internal/config"
"github.com/blinklabs-io/bursa/internal/logging"
"github.com/spf13/cobra"
)

func apiMain() {
cfg := config.GetConfig()
logger := logging.GetLogger()
// Start API listener
logger.Infof(
"starting API listener on %s:%d",
cfg.Api.ListenAddress,
cfg.Api.ListenPort,
)
if err := api.Start(cfg); err != nil {
logger.Fatalf("failed to start API: %s", err)
}
func apiCommand() *cobra.Command {
apiCommand := cobra.Command{
Use: "api",
Short: "Runs the api",
Run: func(cmd *cobra.Command, args []string) {
cfg := config.GetConfig()
// Start API listener
slog.Info(fmt.Sprintf(
"starting API listener on %s:%d",
cfg.Api.ListenAddress,
cfg.Api.ListenPort,
))
if err := api.Start(cfg); err != nil {
slog.Error("failed to start API: %s", err)
os.Exit(1)
}

// Wait forever
select {}
// Wait forever
select {}
},
}
return &apiCommand
}
23 changes: 0 additions & 23 deletions cmd/bursa/cli.go

This file was deleted.

99 changes: 34 additions & 65 deletions cmd/bursa/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,80 +15,49 @@
package main

import (
"flag"
"fmt"
"log/slog"
"os"

"github.com/blinklabs-io/bursa/internal/config"
"github.com/blinklabs-io/bursa/internal/logging"
"github.com/blinklabs-io/bursa/internal/consolelog"
"github.com/spf13/cobra"
)

const (
programName = "bursa"
)

func main() {
var appName string
if os.Args == nil {
appName = "bursa"
} else {
appName = os.Args[0]
}
fs := flag.NewFlagSet(appName, flag.ExitOnError)
fs.Usage = func() {
fmt.Fprintf(
flag.CommandLine.Output(),
"Usage: %s [-h] <subcommand> [args]\n\nSubcommands:\n\n",
appName,
)
fmt.Fprintf(
flag.CommandLine.Output(),
" - %-18s %s\n",
"api",
"run an API server",
)
fmt.Fprintf(
flag.CommandLine.Output(),
" - %-18s %s\n",
"cli",
"run a terminal command",
)
}
if os.Args == nil {
fs.Usage()
os.Exit(1)
}
_ = fs.Parse(os.Args[1:]) // ignore parse errors
globalFlags := struct {
debug bool
}{}

// Load Config
_, err := config.LoadConfig()
if err != nil {
fmt.Printf("Failed to load config: %s\n", err)
os.Exit(1)
rootCmd := &cobra.Command{
Use: programName,
PersistentPreRun: func(cmd *cobra.Command, args []string) {
// Configure default logger
logLevel := slog.LevelInfo
if globalFlags.debug {
logLevel = slog.LevelDebug
}
logger := slog.New(
consolelog.NewHandler(os.Stdout, &slog.HandlerOptions{
Level: logLevel,
}),
)
slog.SetDefault(logger)
},
}
// Configure logging
logging.Setup()
logger := logging.GetLogger()
// Sync logger on exit
defer func() {
if err := logger.Sync(); err != nil {
// ignore error
return
}
}()

var subCommand string
// Parse subcommand
if len(fs.Args()) < 1 {
fs.Usage()
os.Exit(1)
} else {
subCommand = fs.Arg(0)
}
// Global flags
rootCmd.PersistentFlags().BoolVarP(&globalFlags.debug, "debug", "D", false, "enable debug logging")

rootCmd.AddCommand(
newCommand(),
apiCommand(),
)

switch subCommand {
case "api":
apiMain()
case "cli":
cliMain()
default:
fmt.Printf("Unknown subcommand: %s\n", subCommand)
if err := rootCmd.Execute(); err != nil {
// NOTE: we purposely don't display the error, since cobra will have already displayed it
os.Exit(1)
}
}
62 changes: 62 additions & 0 deletions cmd/bursa/new.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Copyright 2024 Blink Labs Software
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
"fmt"

"github.com/blinklabs-io/bursa"
"github.com/blinklabs-io/bursa/internal/cli"
"github.com/spf13/cobra"
)

func newCommand() *cobra.Command {

newCommand := &cobra.Command{
Use: "new",
Short: "Create new things",
}

newCommand.AddCommand(
newWalletCommand(),
//newMnemonicCommand(),
)
return newCommand
}

func newWalletCommand() *cobra.Command {
newWalletCommand := cobra.Command{
Use: "wallet",
Short: "Creates a new wallet",
Long: `Creates mnemonic, payment and stake key pairs)`,
Run: func(cmd *cobra.Command, args []string) {
cli.Run()
},
}

return &newWalletCommand
}

func newMnemonicCommand() *cobra.Command {

Check failure on line 52 in cmd/bursa/new.go

View workflow job for this annotation

GitHub Actions / lint

func `newMnemonicCommand` is unused (unused)
newMnemonicCommand := cobra.Command{
Use: "mnemonic",
Short: "New mnemonic",
Run: func(cmd *cobra.Command, args []string) {
mnemonic, _ := bursa.NewMnemonic()
fmt.Println("Mnemonic ", mnemonic)
},
}
return &newMnemonicCommand
}
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ require (
github.com/go-playground/validator/v10 v10.19.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
Expand All @@ -54,6 +55,8 @@ require (
github.com/prometheus/client_model v0.2.0 // indirect
github.com/prometheus/common v0.32.1 // indirect
github.com/prometheus/procfs v0.7.3 // indirect
github.com/spf13/cobra v1.8.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.12 // indirect
github.com/x448/float16 v0.8.4 // indirect
Expand Down
8 changes: 8 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5P
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
Expand Down Expand Up @@ -196,6 +197,8 @@ github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ
github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/jessevdk/go-flags v0.0.0-20141203071132-1679536dcc89/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
Expand Down Expand Up @@ -286,9 +289,14 @@ github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1
github.com/prometheus/procfs v0.7.3 h1:4jVXhlkAyzOScmCkXBTOLRLTz8EeU+eyjrwB/EPq0VU=
github.com/prometheus/procfs v0.7.3/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88=
github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0=
github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
Expand Down
28 changes: 12 additions & 16 deletions internal/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,16 @@ package api
import (
"fmt"
"net/http"
"time"

ginzap "github.com/gin-contrib/zap"
"log/slog"

Check failure on line 21 in internal/api/api.go

View workflow job for this annotation

GitHub Actions / go-test (1.20.x, ubuntu-latest)

package log/slog is not in GOROOT (/opt/hostedtoolcache/go/1.20.14/x64/src/log/slog)

Check failure on line 21 in internal/api/api.go

View workflow job for this annotation

GitHub Actions / go-test (1.20.x, macos-latest)

package log/slog is not in GOROOT (/Users/runner/hostedtoolcache/go/1.20.14/arm64/src/log/slog)

"github.com/gin-gonic/gin"
"github.com/penglongli/gin-metrics/ginmetrics"
swaggerFiles "github.com/swaggo/files" // swagger embed files
ginSwagger "github.com/swaggo/gin-swagger" // gin-swagger middleware

"github.com/blinklabs-io/bursa"
"github.com/blinklabs-io/bursa/internal/config"
"github.com/blinklabs-io/bursa/internal/logging"

_ "github.com/blinklabs-io/bursa/docs" // docs is generated by Swag CLI
)
Expand Down Expand Up @@ -58,16 +57,14 @@ func Start(cfg *config.Config) error {
router := gin.New()
// Catch panics and return a 500
router.Use(gin.Recovery())
// Standard logging
logger := logging.GetLogger()
// Access logging
accessLogger := logging.GetAccessLogger()
router.Use(ginzap.GinzapWithConfig(accessLogger, &ginzap.Config{
TimeFormat: time.RFC3339,
UTC: true,
SkipPaths: []string{},
}))
router.Use(ginzap.RecoveryWithZap(accessLogger, true))
// accessLogger := logging.GetAccessLogger()
//router.Use(ginzap.GinzapWithConfig(accessLogger, &ginzap.Config{
// TimeFormat: time.RFC3339,
// UTC: true,
// SkipPaths: []string{},
//}))
//router.Use(ginzap.RecoveryWithZap(accessLogger, true))

// Create a healthcheck
router.GET("/healthcheck", handleHealthcheck)
Expand Down Expand Up @@ -111,7 +108,7 @@ func Start(cfg *config.Config) error {
// Start metrics listener
go func() {
// TODO: return error if we cannot initialize metrics
logger.Infof("starting metrics listener on %s:%d",
slog.Info("starting metrics listener on %s:%d",
cfg.Metrics.ListenAddress,
cfg.Metrics.ListenPort,
)
Expand Down Expand Up @@ -145,11 +142,10 @@ func handleHealthcheck(c *gin.Context) {
// @Success 200 {object} bursa.Wallet "Ok"
// @Router /api/wallet/create [get]
func handleWalletCreate(c *gin.Context) {
logger := logging.GetLogger()

mnemonic, err := bursa.NewMnemonic()
if err != nil {
logger.Errorf("failed to load mnemonic: %s", err)
slog.Error("failed to load mnemonic: %s", err)
c.JSON(500, fmt.Sprintf("failed to load mnemonic: %s", err))
_ = ginmetrics.GetMonitor().
GetMetric("bursa_wallets_fail_count").
Expand All @@ -159,7 +155,7 @@ func handleWalletCreate(c *gin.Context) {

w, err := bursa.NewDefaultWallet(mnemonic)
if err != nil {
logger.Errorf("failed to initialize wallet: %s", err)
slog.Error("failed to initialize wallet: %s", err)
c.JSON(500, fmt.Sprintf("failed to initialize wallet: %s", err))
_ = ginmetrics.GetMonitor().
GetMetric("bursa_wallets_fail_count").
Expand Down
Loading

0 comments on commit 258af80

Please sign in to comment.