From 24a4ace6167a43acb8d825832711540f866013d8 Mon Sep 17 00:00:00 2001 From: Farhan Khan Date: Wed, 30 Jun 2021 22:28:53 +0000 Subject: [PATCH] Adding trending to restapi --- restapi/restapi.go | 73 ++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 67 insertions(+), 6 deletions(-) diff --git a/restapi/restapi.go b/restapi/restapi.go index f54485f..5e2eece 100644 --- a/restapi/restapi.go +++ b/restapi/restapi.go @@ -1,20 +1,79 @@ package main import ( + "context" + "encoding/json" "fmt" "log" "net/http" - "strings" - "context" "strconv" - "encoding/json" + "strings" + "time" + "github.com/jackc/pgx/v4" ) +var trendingexport string + func enableCors(w *http.ResponseWriter) { (*w).Header().Set("Access-Control-Allow-Origin", "*") } +func gettrends() { + var err error + var rows pgx.Rows + + for { + rows, err = pool.Query(context.Background(), "SELECT word, ndoc FROM ts_stat($$ SELECT normalized_tsvector FROM activities WHERE activities.identifiedat > current_timestamp - interval '60 minutes' $$) ORDER BY ndoc DESC LIMIT 10") + if err != nil { + panic(err) + } + defer rows.Close() + + trenditems := make([]interface{}, 0) + //fmt.Println(trenditems) + + for rows.Next() { + var word string + var ndoc int + + err = rows.Scan(&word, &ndoc) + if err != nil { + panic(err) + } + + trenditem := make(map[string]interface{}) + trenditem["ndoc"] = ndoc + trenditem["word"] = word + trenditems = append(trenditems, trenditem) + } + + totalJson := make(map[string]interface{}) + totalJson["trends"] = trenditems + + data, err := json.Marshal(totalJson) + if err != nil { + log.Fatal("error marshaling combined activity: %v", err) + } + + trendingexport = string(data) + + time.Sleep(time.Second * 60) + } +} + +func trending(w http.ResponseWriter, r *http.Request) { + enableCors(&w) + + if strings.Contains(r.Header.Get("Accept"), "application/json") { + log.Print("Treat as an Json") + } else { + log.Println("Treat as HTML") + } + + fmt.Fprintf(w, "%s", trendingexport) +} + func search(w http.ResponseWriter, r *http.Request) { enableCors(&w) searchkeys, exists_search := r.URL.Query()["s"] @@ -88,9 +147,8 @@ func search(w http.ResponseWriter, r *http.Request) { requestData := make(map[string]int) requestData["earliestid"] = earliestid - requestData["total_results"] = 9999 - totalJson := make(map[string]interface{} ) + totalJson := make(map[string]interface{}) totalJson["requestdata"] = requestData totalJson["activities"] = activitiesJson @@ -104,7 +162,10 @@ func search(w http.ResponseWriter, r *http.Request) { func main() { pool = getDbPool() + go gettrends() + http.HandleFunc("/search", search) - log.Print("Starting HTTP inbox on port 6431") + http.HandleFunc("/trending", trending) + log.Print("Starting HTTP inbox on port http://0.0.0.0:6431") log.Fatal(http.ListenAndServe("0.0.0.0:6431", nil)) }