rofi-blocks-search/ddg.go

64 lines
1.2 KiB
Go
Raw Normal View History

2020-08-08 16:28:29 +00:00
package main
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
"os"
"os/exec"
2020-08-08 17:14:21 +00:00
"./rofi"
)
2020-08-08 16:28:29 +00:00
func getSuggestions(query string) []string {
param := url.Values{}
param.Add("q", query)
param.Add("type", "list")
param.Add("kl", "en-US")
resp, _ := http.Get("https://ac.duckduckgo.com/ac?" + param.Encode())
body, _ := ioutil.ReadAll(resp.Body)
resp.Body.Close()
var result []interface{}
json.Unmarshal(body, &result)
if len(result) < 2 {
2020-08-08 20:37:33 +00:00
return []string{query}
2020-08-08 16:28:29 +00:00
}
2020-08-08 20:37:33 +00:00
rtn := make([]string, len(result[1].([]interface{}))+1)
rtn[0] = query
2020-08-08 16:28:29 +00:00
for i, v := range result[1].([]interface{}) {
2020-08-08 20:37:33 +00:00
rtn[i+1] = v.(string)
2020-08-08 16:28:29 +00:00
}
return rtn
}
2020-08-08 17:14:21 +00:00
func handleSelect(input rofi.Input) {
param := url.Values{}
param.Add("q", input.Value)
exec.Command("xdg-open", "https://duckduckgo.com/?"+param.Encode()).Start()
os.Exit(0)
2020-08-08 16:28:29 +00:00
}
2020-08-08 17:14:21 +00:00
func handleInputChange(input rofi.Input) {
output := rofi.NewOutput()
output.Lines = rofi.ConvertStringsToLine(getSuggestions(input.Value))
rofi.SendOutput(output)
2020-08-08 16:28:29 +00:00
}
func main() {
// Setup rofi
2020-08-08 17:14:21 +00:00
initialOutput := rofi.NewOutput()
2020-08-08 16:28:29 +00:00
initialOutput.Prompt = "Search"
initialOutput.InputAction = "send"
2020-08-08 17:14:21 +00:00
rofi.SendOutput(initialOutput)
2020-08-08 16:28:29 +00:00
2020-08-08 17:14:21 +00:00
rofi.InputChangeCallback = handleInputChange
rofi.SelectEntryCallback = handleSelect
rofi.InputLoop()
2020-08-08 16:28:29 +00:00
}