这是indexloc提供的服务,不要输入任何密码
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions go-gopher-cli/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# go-gopher-cli

[![Go Report Card](https://goreportcard.com/badge/github.com/AymenSegni/go-examples/go-gopher-cli)](https://goreportcard.com/report/github.com/AymenSegni/go-examples/go-gopher-cli)

This repo contains a simple CLI (Command Line Interface) application in Go, with a basic code organization.
We use:
* net/http package to retrieve our cute Gophers
* Cobra for creating powerful modern CLI applications
* Viper to ...

go-gopher-cli use [Taskfile](https://dev.to/stack-labs/introduction-to-taskfile-a-makefile-alternative-h92) (a Makefile alternative).

## Pre-requisits

Install Go in 1.16.x version minimum.

## Build the app

```bash
go build -o bin/go-gopher-cli main.go
```

or

```bash
task build
```

## Run the app

```bash
./bin/go-gopher-cli
```

or

```
task run
```

## Test the app

```bash
./bin/gopher-cli
Gopher CLI application written in Go.

Usage:
go-gopher-cli [command]

Available Commands:
completion generate the autocompletion script for the specified shell
get This command will return the requested Gopher if it exist
help Help about any command
...


./bin/gopher-cli get friends
Try to get 'friends' Gopher...
Perfect! Just saved in friends.png!

file friends.png
friends.png: PNG image data, 1156 x 882, 8-bit/color RGBA, non-interlaced
```
Binary file added go-gopher-cli/bin/gopher-cli
Binary file not shown.
82 changes: 82 additions & 0 deletions go-gopher-cli/cmd/get.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/*
Copyright © 2021 Aymen Segni: segniaymen1@gmail.com

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 cmd

import (
"fmt"
"io"
"net/http"
"os"

"github.com/spf13/cobra"
)

// getCmd represents the get command
var getCmd = &cobra.Command{
Use: "get",
Short: "This command will return the requested Gopher if it exist",
Long: "This get command will browse scraly/gophers repository and fetch the desired Gopher .",
Run: func(cmd *cobra.Command, args []string) {
// init the Gopher with var
var gopherName = "dr-who.png"

// make sure that the gopher given by the user isn't empty
if len (args) >= 1 && args[0] != "" {
gopherName = args[0]
}

// define the gopher URL

URL := "https://github.com/scraly/gophers/raw/main/" + gopherName + ".png"
fmt.Println("get'" + gopherName + "'Gopher ..")

// get the gopher content
response, err := http.Get(URL)

// error handling
if err != nil {
fmt.Println(err)
}
// close function connection
defer response.Body.Close()

// in case we get the desired gopher
if response.StatusCode == 200 {
// create the gopher file locally
out, err := os.Create(gopherName + ".png")

defer out.Close()

// write body file
_, err = io.Copy(out, response.Body)
if err != nil {
fmt.Println(err)
}

// log the succeed msg
fmt.Println("gopher is downloaded and saved successfly in " + out.Name())

} else {
fmt.Println("Error: " + gopherName + " not exists! :-(")
}

},
}

// add getCmd comand
func init() {
rootCmd.AddCommand(getCmd)
}
80 changes: 80 additions & 0 deletions go-gopher-cli/cmd/root.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/*
Copyright © 2021 Aymen Segni: segniaymen1@gmail.com

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 cmd

import (
"fmt"
"os"
"github.com/spf13/cobra"

"github.com/spf13/viper"
)

var cfgFile string

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "get",
Short: "This command will return the requested Gopher if it exist",
Long: "This get command will browse scraly/gophers repository and fetch the desired Gopher .",
// Uncomment the following line if your bare application
// has an action associated with it:
// Run: func(cmd *cobra.Command, args []string) { },
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
cobra.CheckErr(rootCmd.Execute())
}

func init() {
cobra.OnInitialize(initConfig)

// Here you will define your flags and configuration settings.
// Cobra supports persistent flags, which, if defined here,
// will be global for your application.

rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.go-gopher-cli.yaml)")

// Cobra also supports local flags, which will only run
// when this action is called directly.
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Find home directory.
home, err := os.UserHomeDir()
cobra.CheckErr(err)

// Search config in home directory with name ".go-gopher-cli" (without extension).
viper.AddConfigPath(home)
viper.SetConfigType("yaml")
viper.SetConfigName(".go-gopher-cli")
}

viper.AutomaticEnv() // read in environment variables that match

// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed())
}
}
11 changes: 11 additions & 0 deletions go-gopher-cli/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
module github.com/AymenSegni/go-examples/go-gopher-cli

go 1.16

require (
github.com/spf13/cast v1.4.0 // indirect
github.com/spf13/cobra v1.2.1
github.com/spf13/viper v1.8.1
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e // indirect
golang.org/x/text v0.3.7 // indirect
)
Loading