Adding trending to restapi

This commit is contained in:
Farhan Khan 2021-06-30 22:28:53 +00:00
parent 395280c600
commit 24a4ace616

View File

@ -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,7 +147,6 @@ 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["requestdata"] = requestData
@ -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))
}