bangs/evaluator.go

84 lines
2 KiB
Go
Raw Normal View History

2019-05-26 22:36:46 +02:00
package main
import (
2019-06-12 13:49:00 +02:00
"log"
"net/http"
"net/url"
2021-01-05 12:40:26 +01:00
"os"
2019-05-26 22:36:46 +02:00
"regexp"
2019-06-12 13:49:00 +02:00
"strings"
2019-05-26 22:36:46 +02:00
)
//go:generate go run scripts/includebangs.go
2019-05-26 22:36:46 +02:00
func main() {
http.HandleFunc("/eval", func(w http.ResponseWriter, r *http.Request) {
searchQuery := r.URL.Query().Get("query")
searchEngine := r.URL.Query().Get("engine")
2021-01-04 21:04:16 +01:00
if searchQuery == "" || searchEngine == "" {
2019-05-26 22:36:46 +02:00
http.Error(w, "400 Bad Request", http.StatusBadRequest)
return
}
searchQuery, searchEngine = evaluateBang(searchQuery, searchEngine)
searchURL := buildSearchURL(searchEngine, searchQuery)
http.Redirect(w, r, searchURL, http.StatusSeeOther)
})
2021-01-05 12:40:26 +01:00
listenAddress := getSetting("LISTEN_ADDRESS", ":8081")
log.Printf("Listening at %s", listenAddress)
log.Fatalf("Failed to start http server: %v", http.ListenAndServe(listenAddress, nil))
}
func getenv(name string, fallback string) (value string) {
value = os.Getenv(name)
if value == "" {
return fallback
}
return
}
func getSetting(name, fallback string) (value string) {
return getenv("BANG_EVALUATOR_"+name, fallback)
2019-05-26 22:36:46 +02:00
}
func buildSearchURL(template string, query string) (searchUrl string) {
searchUrl = strings.Replace(template, "%s", url.QueryEscape(query), 1)
2019-06-13 16:00:24 +02:00
searchUrl = strings.Replace(searchUrl, "%S", query, 1)
return searchUrl
2019-05-26 22:36:46 +02:00
}
func parseBang(searchQuery string) (bang string, query string) {
regexStartBang, _ := regexp.Compile("\\!(.*) (.*)")
regexEndBang, _ := regexp.Compile("(.*) \\!(.*)")
startBang := regexStartBang.FindSubmatch([]byte(searchQuery))
endBang := regexEndBang.FindSubmatch([]byte(searchQuery))
if len(endBang) == 3 {
2019-05-30 21:04:16 +02:00
bang = strings.ToLower(string(endBang[2]))
query = string(endBang[1])
return
2019-05-26 22:36:46 +02:00
} else if len(startBang) == 3 {
2019-05-30 21:04:16 +02:00
bang = strings.ToLower(string(startBang[1]))
query = string(startBang[2])
return
2019-05-26 22:36:46 +02:00
} else {
return "", searchQuery
}
}
func evaluateBang(searchQuery string, searchEngine string) (query string, engine string) {
bang, query := parseBang(searchQuery)
engine = getBang(bang)
2021-01-04 21:04:16 +01:00
if bang == "" || engine == "" {
return searchQuery, searchEngine
2019-05-26 22:36:46 +02:00
} else {
return query, engine
2019-05-26 22:36:46 +02:00
}
}