From e52c9e9eb232fe4ea15fb62475accc7759eeaa69 Mon Sep 17 00:00:00 2001 From: gi8 Date: Wed, 20 Dec 2023 16:17:10 +0100 Subject: [PATCH] rename fetch to pull & fix commands pull & push --- README.md | 6 ++--- cmd/{fetch.go => pull.go} | 51 +++++++++++++++++++++++------------- cmd/push.go | 50 +++++++++++++++++++---------------- cmd/root.go | 10 ++++++- internal/config/structs.go | 1 + internal/handlers/home.go | 1 + internal/handlers/structs.go | 1 + web/templates/index.html | 1 + 8 files changed, 76 insertions(+), 45 deletions(-) rename cmd/{fetch.go => pull.go} (50%) diff --git a/README.md b/README.md index bc2b666..8a01d52 100644 --- a/README.md +++ b/README.md @@ -53,12 +53,12 @@ Push data to the `vimbin` server: | `-u`, `--url` `URL` | The URL of the vimbin server | | `-h`, `--help` | help for push | -### Fetch +### Pull -Fetch the latest data from the `vimbin` server: +Pull the latest data from the `vimbin` server: ```bash -./vimbin fetch +./vimbin pull ``` **Flags:** diff --git a/cmd/fetch.go b/cmd/pull.go similarity index 50% rename from cmd/fetch.go rename to cmd/pull.go index 6b4867e..ce1dea7 100644 --- a/cmd/fetch.go +++ b/cmd/pull.go @@ -18,49 +18,64 @@ package cmd import ( "fmt" "io" - "os" + "net/http" "strings" "vimbin/internal/config" "vimbin/internal/utils" "github.com/rs/zerolog/log" - "github.com/spf13/cobra" ) -// fetchCmd represents the 'fetch' command for retrieving the latest data from the vimbin server. -var fetchCmd = &cobra.Command{ - Use: "fetch", - Short: "Fetches the latest data from the vimbin server", - Long: `The 'fetch' command retrieves the latest content from the vimbin server specified by the provided URL. +// pullCmd represents the 'fetch' command for retrieving the latest data from the vimbin server. +var pullCmd = &cobra.Command{ + Use: "pull", + Short: "Pulls the latest data from the vimbin server", + Long: `The 'pull' command retrieves the latest content from the vimbin server specified by the provided URL. It makes a GET request to the server and prints the response body to the console. Example: - vimbin fetch --url http://example.com`, + vimbin pull --url http://example.com`, Run: func(cmd *cobra.Command, args []string) { url := strings.TrimSuffix(config.App.Server.Api.Address, "/") if url == "" { - log.Error().Msg("URL is empty") - os.Exit(1) + log.Fatal().Msg("URL is empty") } url += "/fetch" + log.Debug().Msgf("URL: %s", url) + + apiToken := config.App.Server.Api.Token.Get() + if apiToken == "" { + log.Fatal().Msg("API token is empty") + } httpClient := utils.CreateHTTPClient(config.App.Server.Api.SkipInsecureVerify) + req, err := http.NewRequest("GET", url, nil) + if err != nil { + log.Fatal().Msgf("Error creating HTTP request: %v", err) + } + + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-API-Token", apiToken) // Make a GET request to the vimbin server - response, err := httpClient.Get(url) + response, err := httpClient.Do(req) if err != nil { log.Error().Msgf("Error making GET request: %s", err) return } defer response.Body.Close() + // Check for successful response + if response.StatusCode != http.StatusOK { + log.Fatal().Msgf("Unexpected status code %d", response.StatusCode) + } + // Read the response body body, err := io.ReadAll(response.Body) if err != nil { - log.Error().Msgf("Error reading response body: %s", err) - return + log.Fatal().Msgf("Error reading response body: %s", err) } // Print the content to the console @@ -69,10 +84,10 @@ Example: } func init() { - // Add 'fetchCmd' to the root command - rootCmd.AddCommand(fetchCmd) + // Add 'pullCmd' to the root command + rootCmd.AddCommand(pullCmd) - // Define command-line flags for 'fetchCmd' - fetchCmd.PersistentFlags().StringVarP(&config.App.Server.Api.Address, "url", "u", "", "The URL of the vimbin server") - fetchCmd.PersistentFlags().BoolVarP(&config.App.Server.Api.SkipInsecureVerify, "insecure-skip-verify", "i", false, "Skip TLS certificate verification") + // Define command-line flags for 'pullCmd' + pullCmd.PersistentFlags().StringVarP(&config.App.Server.Api.Address, "url", "u", "", "The URL of the vimbin server") + pullCmd.PersistentFlags().BoolVarP(&config.App.Server.Api.SkipInsecureVerify, "insecure-skip-verify", "i", false, "Skip TLS certificate verification") } diff --git a/cmd/push.go b/cmd/push.go index db32c0a..84ed109 100644 --- a/cmd/push.go +++ b/cmd/push.go @@ -21,7 +21,6 @@ import ( "fmt" "io" "net/http" - "os" "strings" "vimbin/internal/config" "vimbin/internal/utils" @@ -49,68 +48,73 @@ Examples: Run: func(cmd *cobra.Command, args []string) { // Check if at least one character is provided if len(args) < 1 { - log.Error().Msg("You must push at least one character.") - os.Exit(1) + log.Fatal().Msg("You must push at least one character.") } url := strings.TrimSuffix(config.App.Server.Api.Address, "/") if url == "" { - log.Error().Msg("URL is empty") - os.Exit(1) + log.Fatal().Msg("URL is empty") + } + + apiToken := config.App.Server.Api.Token.Get() + if apiToken == "" { + log.Fatal().Msg("API token is empty") } // Concatenate input arguments into a single string - body := strings.Join(args, "\n") + input := strings.Join(args, "\n") // Build the URL based on the "append" flag if appendFlag { url += "/append" - body = "\n" + body + input = "\n" + input } else { url += "/save" } // Prepare content for the POST request - content := map[string]string{"content": body} + content := map[string]string{"content": input} requestBody, err := json.Marshal(content) if err != nil { - log.Error().Msgf("Error encoding JSON: %s", err) - os.Exit(1) + log.Fatal().Msgf("Error encoding JSON: %s", err) } httpClient := utils.CreateHTTPClient(config.App.Server.Api.SkipInsecureVerify) + req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody)) + if err != nil { + log.Fatal().Msgf("Error creating HTTP request: %v", err) + } + + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-API-Token", apiToken) // Make the POST request to the vimbin server - response, err := httpClient.Post(url, "application/json", bytes.NewBuffer(requestBody)) + response, err := httpClient.Do(req) if err != nil { - log.Error().Msgf("Error making POST request: %s", err) - os.Exit(1) + log.Fatal().Msgf("Error making POST request: %s", err) } defer response.Body.Close() // Check for successful response if response.StatusCode != http.StatusOK { - log.Error().Msgf("Unexpected status code %d", response.StatusCode) - os.Exit(1) + log.Fatal().Msgf("Unexpected status code %d", response.StatusCode) } - // Read and print the response body - var responseBodyBuffer bytes.Buffer - _, err = io.Copy(&responseBodyBuffer, response.Body) + body, err := io.ReadAll(response.Body) if err != nil { - log.Error().Msgf("Error reading response body: %s", err) - os.Exit(1) + log.Fatal().Msgf("Error reading response body: %s", err) } - fmt.Println(responseBodyBuffer.String()) + // Print the content to the console + fmt.Println(string(body)) }, } func init() { - // Add 'fetchCmd' to the root command + // Add 'pullCmd' to the root command rootCmd.AddCommand(pushCmd) - // Define command-line flags for 'fetchCmd' + // Define command-line flags for 'pullCmd' pushCmd.PersistentFlags().StringVarP(&config.App.Server.Api.Address, "url", "u", "", "The URL of the vimbin server") pushCmd.PersistentFlags().BoolVarP(&config.App.Server.Api.SkipInsecureVerify, "insecure-skip-verify", "i", false, "Skip TLS certificate verification") pushCmd.PersistentFlags().BoolVarP(&appendFlag, "append", "a", false, "Append content to the existing content") diff --git a/cmd/root.go b/cmd/root.go index 8cdf343..b36604b 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -30,7 +30,7 @@ import ( ) const ( - version = "v0.0.14" + version = "v0.0.16" ) var ( @@ -53,6 +53,9 @@ var rootCmd = &cobra.Command{ - push: Quickly send text to the vimbin server from the command line. This allows for easy integration with other tools and scripts, streamlining the process of sharing content through vimbin. + +- pull: Retrieve the latest content from the vimbin server. This allows for easy integration with other + tools and scripts, streamlining the process of retrieving content from vimbin. `, PersistentPreRun: func(cmd *cobra.Command, args []string) { // PersistentPreRun is executed before any subcommand is executed. @@ -65,6 +68,7 @@ var rootCmd = &cobra.Command{ // Configure zerolog zerolog.TimeFieldFormat = zerolog.TimeFormatUnix + zerolog.SetGlobalLevel(zerolog.InfoLevel) output := zerolog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.RFC3339} log.Logger = zerolog.New(output).With().Timestamp().Logger() @@ -85,9 +89,13 @@ var rootCmd = &cobra.Command{ log.Debug().Msgf("Trace output enabled") } + // Save token to config if token := cmd.Flag("token").Value.String(); token != "" { config.App.Server.Api.Token.Set(token) } + + config.App.Version = version + log.Debug().Msgf("Version: %s", config.App.Version) }, Run: func(cmd *cobra.Command, args []string) { // Run is executed if no subcommand is specified. diff --git a/internal/config/structs.go b/internal/config/structs.go index 0c051c4..7f8849f 100644 --- a/internal/config/structs.go +++ b/internal/config/structs.go @@ -11,6 +11,7 @@ var App Config // Config represents the application configuration. type Config struct { + Version string `mapstructure:"-"` // Version is the version of the application. HtmlTemplate *template.Template `mapstructure:"-"` // HtmlTemplate contains the HTML template content. Server Server `mapstructure:"server"` // Server represents the server configuration. Storage Storage `mapstructure:"storage"` // Storage represents the storage configuration. diff --git a/internal/handlers/home.go b/internal/handlers/home.go index 0330169..8f4e1a4 100644 --- a/internal/handlers/home.go +++ b/internal/handlers/home.go @@ -31,6 +31,7 @@ func Home(w http.ResponseWriter, r *http.Request) { Content: config.App.Storage.Content.Get(), Token: config.App.Server.Api.Token.Get(), Theme: config.App.Server.Web.Theme, + Version: config.App.Version, } if err := config.App.HtmlTemplate.Execute(w, page); err != nil { diff --git a/internal/handlers/structs.go b/internal/handlers/structs.go index 19f4856..d3fc115 100644 --- a/internal/handlers/structs.go +++ b/internal/handlers/structs.go @@ -9,4 +9,5 @@ type Page struct { Content string // Content is the content of the page. Token string // Token is the API token. Theme string // Theme is the theme of the page. + Version string // Version is the version of the application. } diff --git a/web/templates/index.html b/web/templates/index.html index d46e281..a7bd436 100644 --- a/web/templates/index.html +++ b/web/templates/index.html @@ -3,6 +3,7 @@ + vimbin - a pastebin with vim motion