| 1 |
package main |
| 2 |
|
| 3 |
import ( |
| 4 |
"encoding/json" |
| 5 |
"net/http" |
| 6 |
"net/url" |
| 7 |
"strings" |
| 8 |
"sync" |
| 9 |
|
| 10 |
"github.com/gdamore/tcell/v2" |
| 11 |
"github.com/rivo/tview" |
| 12 |
) |
| 13 |
|
| 14 |
type company struct { |
| 15 |
Name string `json:"name"` |
| 16 |
} |
| 17 |
|
| 18 |
func main() { |
| 19 |
app := tview.NewApplication() |
| 20 |
inputField := tview.NewInputField(). |
| 21 |
SetLabel("Enter a company name: "). |
| 22 |
SetFieldWidth(30). |
| 23 |
SetDoneFunc(func(key tcell.Key) { |
| 24 |
app.Stop() |
| 25 |
}) |
| 26 |
|
| 27 |
|
| 28 |
var mutex sync.Mutex |
| 29 |
prefixMap := make(map[string][]string) |
| 30 |
inputField.SetAutocompleteFunc(func(currentText string) []string { |
| 31 |
|
| 32 |
prefix := strings.TrimSpace(strings.ToLower(currentText)) |
| 33 |
if prefix == "" { |
| 34 |
return nil |
| 35 |
} |
| 36 |
|
| 37 |
|
| 38 |
mutex.Lock() |
| 39 |
defer mutex.Unlock() |
| 40 |
entries, ok := prefixMap[prefix] |
| 41 |
if ok { |
| 42 |
return entries |
| 43 |
} |
| 44 |
|
| 45 |
|
| 46 |
go func() { |
| 47 |
|
| 48 |
url := "https://autocomplete.clearbit.com/v1/companies/suggest?query=" + url.QueryEscape(prefix) |
| 49 |
res, err := http.Get(url) |
| 50 |
if err != nil { |
| 51 |
return |
| 52 |
} |
| 53 |
|
| 54 |
|
| 55 |
var companies []*company |
| 56 |
dec := json.NewDecoder(res.Body) |
| 57 |
if err := dec.Decode(&companies); err != nil { |
| 58 |
return |
| 59 |
} |
| 60 |
entries := make([]string, 0, len(companies)) |
| 61 |
OuterLoop: |
| 62 |
for _, c := range companies { |
| 63 |
for _, entry := range entries { |
| 64 |
if strings.EqualFold(entry, c.Name) { |
| 65 |
continue OuterLoop |
| 66 |
} |
| 67 |
} |
| 68 |
entries = append(entries, c.Name) |
| 69 |
} |
| 70 |
mutex.Lock() |
| 71 |
prefixMap[prefix] = entries |
| 72 |
mutex.Unlock() |
| 73 |
|
| 74 |
|
| 75 |
inputField.Autocomplete() |
| 76 |
|
| 77 |
|
| 78 |
app.Draw() |
| 79 |
}() |
| 80 |
|
| 81 |
return nil |
| 82 |
}) |
| 83 |
|
| 84 |
if err := app.EnableMouse(true).SetRoot(inputField, true).Run(); err != nil { |
| 85 |
panic(err) |
| 86 |
} |
| 87 |
} |