Create Vocabulary English CLI Application with Golang

Aplikasi yang diharapkan adalah menampilkan word in english secara random bersama meaning dan examplenya setiap membuka Command Line
Tujuan atau manfaat: Memperkaya kosakata bahasa English

Dependencies

  1. Framework CLI golang : github.com/urfave/cli/v2
  2. API Dictionary : https://api.dictionaryapi.dev/api/v2/entries/en/
  3. List English word : https://github.com/bitcoinjs/bip39/blob/master/src/wordlists/english.json
  4. Coloring text on Terminal : github.com/fatih/color

Struktur Folder

/vocabulary
├── go.mod
├── go.sum
├── vocabulary.go
└── word.json
package main

import (
  _ "embed"
  "encoding/json"
  "fmt"
  "github.com/fatih/color"
  "io/ioutil"
  "log"
  "math/rand"
  "net/http"
  "os"
  "strings"
  "time"

  "github.com/urfave/cli/v2"
)

// ResponseDictionary converted by https://mholt.github.io/json-to-go/
type ResponseDictionary []struct {
  Word       string      `json:"word"`
  Phonetic   string      `json:"phonetic"`
  Phonetics  []Phonetics `json:"phonetics"`
  Meanings   []Meanings  `json:"meanings"`
  License    License     `json:"license"`
  SourceUrls []string    `json:"sourceUrls"`
}
type License struct {
  Name string `json:"name"`
  URL  string `json:"url"`
}
type Phonetics struct {
  Text      string  `json:"text"`
  Audio     string  `json:"audio"`
  SourceURL string  `json:"sourceUrl,omitempty"`
  License   License `json:"license,omitempty"`
}
type Definitions struct {
  Definition string        `json:"definition"`
  Synonyms   []interface{} `json:"synonyms"`
  Antonyms   []interface{} `json:"antonyms"`
  Example    string        `json:"example,omitempty"`
}
type Meanings struct {
  PartOfSpeech string        `json:"partOfSpeech"`
  Definitions  []Definitions `json:"definitions"`
  Synonyms     []interface{} `json:"synonyms"`
  Antonyms     []interface{} `json:"antonyms"`
}

type Word []string

//go:embed word.json
var wordJson []byte

func main() {
  app := &cli.App{
    Name: "vocabulary",
    Usage: "get a word today",
    Action: func(c *cli.Context) error {

      var word Word
      err := json.Unmarshal(wordJson, &word)
      if err != nil {
        return nil
      }

      rand.Seed(time.Now().UnixNano())
      min := 0
      max := len(word)
      randomNumber := rand.Intn(max - min + 1) + min
      wordToday := word[randomNumber]
      URIBuilt := fmt.Sprintf("https://api.dictionaryapi.dev/api/v2/entries/en/%v", wordToday)
      response, err := http.Get(URIBuilt)

      if err != nil {
        fmt.Print(err.Error())
        os.Exit(1)
      }

      responseData, err := ioutil.ReadAll(response.Body)

      var responseDictionary ResponseDictionary
      err = json.Unmarshal(responseData, &responseDictionary)
      if err != nil {
        log.Fatal(err)
      }
      color.Set(color.FgYellow)
      fmt.Println("Word:",strings.ToTitle(strings.ToLower(responseDictionary[0].Word)))
      color.Unset()
      fmt.Println("Meaning:", responseDictionary[0].Meanings[0].Definitions[0].Definition)

      if responseDictionary[0].Meanings[0].Definitions[0].Example  != "" {
        fmt.Println("Example:", responseDictionary[0].Meanings[0].Definitions[0].Example)
      }
      return nil
    },
  }

  err := app.Run(os.Args)
  if err != nil {
    log.Fatal(err)
  }
}

cd vocabulary
go install
go build

Biar setiap buka Comman Line otomatis jalanin aplikasi golang, buka menu preferences di terminal ZSH, isi Login Shell dengan lokasi executed golang application

 

Source code on GitHub: https://github.com/myusufid/vocabulary-cli-golang













Belajar Sorting a String and Write to File with Golang

Belajar sorting sebuah string dari argument terminal dan tulis ke sebuah file.

Expected Output:
go run main.go orange banana apple

cat sorted.txt   
     apple banana orange
package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"sort"
)

func main() {
	// get all arguments
	items := os.Args[1:]

	if len(items) == 0 {
		fmt.Println("Send me some items and I will sort them")
		return
	}
	// String slices are sortable using `sort.Strings`
	sort.Strings(items)


	var data []byte
	for _, s := range items {
		// append a string to a byte slice
		data = append(data, s...)
	}

	err := ioutil.WriteFile("sorted.txt", data, 0644)
	if err != nil {
		fmt.Println(err)
		return
	}
}

Output:

 

Source :
https://github.com/inancgumus/learngo/blob/master/17-project-empty-file-finder/exercises/1-sort-to-a-file/main.go













Belajar Command Line Arguments Golang

Golang punya package called as Args
Args adalah string berbentuk array berisi command line arguments

Examples:
The first argument

package main
  
import (
    "fmt"
    "os"
)
  
func main() {
    // The first argument is always program name
    myProgramName := os.Args[0]
      
    // it will display the program name
    fmt.Println(myProgramName)
}

Output:

Get all arguments

package main
  
import (
    "fmt"
    "os"
)
  
func main() {
    allArgs := os.Args[1:]
    fmt.Println(allArgs)
}

Output: