Rewriting to go.
This commit is contained in:
parent
d9e72f756d
commit
1dd218626b
4 changed files with 112 additions and 12 deletions
90
main.go
Normal file
90
main.go
Normal file
|
@ -0,0 +1,90 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/fatih/color"
|
||||
)
|
||||
|
||||
// Define json structure holder
|
||||
type Word struct {
|
||||
List []struct {
|
||||
Definition string `json:"definition"`
|
||||
Permalink string `json:"permalink"`
|
||||
ThumbsUp int `json:"thumbs_up"`
|
||||
Author string `json:"author"`
|
||||
Word string `json:"word"`
|
||||
Defid int `json:"defid"`
|
||||
CurrentVote string `json:"current_vote"`
|
||||
WrittenOn time.Time `json:"written_on"`
|
||||
Example string `json:"example"`
|
||||
ThumbsDown int `json:"thumbs_down"`
|
||||
} `json:"list"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
// get how many result we wan't for the specific word
|
||||
num := flag.Int("n", 1, "Amount of results to print out")
|
||||
|
||||
flag.Parse()
|
||||
|
||||
var unknownWord string
|
||||
|
||||
// Check if word was provided as cli argument, if not ask user to input it
|
||||
if flag.NArg() == 0 {
|
||||
fmt.Print("Enter word the check meaning off: ")
|
||||
scanner := bufio.NewScanner(os.Stdin)
|
||||
scanner.Scan()
|
||||
err := scanner.Err()
|
||||
if err != nil {
|
||||
fmt.Println("Error reading user input")
|
||||
os.Exit(1)
|
||||
}
|
||||
unknownWord = strings.ReplaceAll(scanner.Text(), " ", "%20")
|
||||
fmt.Println()
|
||||
} else {
|
||||
unknownWord = strings.Join(flag.Args(), "%20")
|
||||
}
|
||||
|
||||
// Get response from url
|
||||
res, err := http.Get("https://api.urbandictionary.com/v0/define?term=" + unknownWord)
|
||||
if err != nil {
|
||||
fmt.Printf("error making http request %s", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Read the body of message
|
||||
defer res.Body.Close()
|
||||
body, err := io.ReadAll(res.Body)
|
||||
if err != nil {
|
||||
fmt.Printf("error reading the body %s", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Read the json and parse it
|
||||
var word Word
|
||||
if err := json.Unmarshal(body, &word); err != nil {
|
||||
fmt.Println("Can not unmarshal json")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Print out the needed amount of results, or exit if not enough results
|
||||
for i := 0; i < *num; i++ {
|
||||
if i == len(word.List) {
|
||||
break
|
||||
}
|
||||
color.Cyan(word.List[i].Word)
|
||||
fmt.Println(word.List[i].Definition)
|
||||
if *num > 1 {
|
||||
fmt.Println()
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue