rofi-blocks-search/ddg.go
2020-08-08 20:56:09 +02:00

63 lines
1.2 KiB
Go

package main
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
"os"
"os/exec"
"./rofi"
)
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 {
return []string{}
}
rtn := make([]string, len(result[1].([]interface{})))
for i, v := range result[1].([]interface{}) {
rtn[i] = v.(string)
}
return rtn
}
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)
}
func handleInputChange(input rofi.Input) {
output := rofi.NewOutput()
output.Lines = rofi.ConvertStringsToLine(getSuggestions(input.Value))
rofi.SendOutput(output)
}
func main() {
// Setup rofi
initialOutput := rofi.NewOutput()
initialOutput.Prompt = "Search"
initialOutput.InputAction = "send"
rofi.SendOutput(initialOutput)
rofi.InputChangeCallback = handleInputChange
rofi.SelectEntryCallback = handleSelect
rofi.InputLoop()
}