Skip to content

Commit

Permalink
Refactor: merge command
Browse files Browse the repository at this point in the history
  • Loading branch information
Loyalsoldier committed Nov 2, 2024
1 parent 7f5d3a7 commit 3ea8192
Showing 1 changed file with 40 additions and 79 deletions.
119 changes: 40 additions & 79 deletions merge.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,75 +5,10 @@ import (
"strings"

"github.com/Loyalsoldier/geoip/lib"
"github.com/Loyalsoldier/geoip/plugin/special"
"github.com/spf13/cobra"
)

const tempConfig = `
{
"input": [
{
"type": "stdin",
"action": "add",
"args": {
"name": "temp"
}
}
],
"output": [
{
"type": "stdout",
"action": "output"
}
]
}
`

const tempConfigWithIPv4 = `
{
"input": [
{
"type": "stdin",
"action": "add",
"args": {
"name": "temp"
}
}
],
"output": [
{
"type": "stdout",
"action": "output",
"args": {
"onlyIPType": "ipv4"
}
}
]
}
`

const tempConfigWithIPv6 = `
{
"input": [
{
"type": "stdin",
"action": "add",
"args": {
"name": "temp"
}
}
],
"output": [
{
"type": "stdout",
"action": "output",
"args": {
"onlyIPType": "ipv6"
}
}
]
}
`

func init() {
rootCmd.AddCommand(mergeCmd)
mergeCmd.PersistentFlags().StringP("onlyiptype", "t", "", "The only IP type to output, available options: \"ipv4\", \"ipv6\"")
Expand All @@ -91,27 +26,53 @@ var mergeCmd = &cobra.Command{
log.Fatal("invalid argument onlyiptype: ", otype)
}

var configBytes []byte
switch lib.IPType(otype) {
case lib.IPv4:
configBytes = []byte(tempConfigWithIPv4)
case lib.IPv6:
configBytes = []byte(tempConfigWithIPv6)
default:
configBytes = []byte(tempConfig)
}

instance, err := lib.NewInstance()
if err != nil {
log.Fatal(err)
}

if err := instance.InitConfigFromBytes(configBytes); err != nil {
log.Fatal(err)
}
instance.AddInput(getInputForMerge())
instance.AddOutput(getOutputForMerge(otype))

if err := instance.Run(); err != nil {
log.Fatal(err)
}
},
}

func getInputForMerge() lib.InputConverter {
return &special.Stdin{
Type: special.TypeStdin,
Action: lib.ActionAdd,
Description: special.DescStdin,
Name: "temp",
}
}

func getOutputForMerge(otype string) lib.OutputConverter {
switch lib.IPType(otype) {
case lib.IPv4:
return &special.Stdout{
Type: special.TypeStdout,
Action: lib.ActionOutput,
Description: special.DescStdout,
OnlyIPType: lib.IPv4,
}

case lib.IPv6:
return &special.Stdout{
Type: special.TypeStdout,
Action: lib.ActionOutput,
Description: special.DescStdout,
OnlyIPType: lib.IPv6,
}

default:
return &special.Stdout{
Type: special.TypeStdout,
Action: lib.ActionOutput,
Description: special.DescStdout,
}
}

}

0 comments on commit 3ea8192

Please sign in to comment.