79 lines
2.0 KiB
Go
79 lines
2.0 KiB
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"log"
|
||
|
"net/http"
|
||
|
"strings"
|
||
|
"context"
|
||
|
_ "strconv"
|
||
|
"encoding/json"
|
||
|
"github.com/jackc/pgx/v4"
|
||
|
)
|
||
|
|
||
|
func search(w http.ResponseWriter, r *http.Request) {
|
||
|
searchkeys, exists := r.URL.Query()["s"]
|
||
|
|
||
|
if strings.Contains(r.Header.Get("Accept"), "application/json") {
|
||
|
log.Print("Treat as an Json")
|
||
|
} else {
|
||
|
log.Println("Treat as HTML")
|
||
|
}
|
||
|
|
||
|
|
||
|
var err error
|
||
|
var rows pgx.Rows
|
||
|
var searchKey string
|
||
|
if exists {
|
||
|
searchKey = searchkeys[0]
|
||
|
}
|
||
|
|
||
|
if exists && searchKey != "" {
|
||
|
rows, err = pool.Query(context.Background(), "SELECT activities.id, activities.document, actors.document FROM activities as activities INNER JOIN actors as actors ON activities.document->>'actor' = actors.document->>'id' WHERE activities.normalized_tsvector @@ plainto_tsquery($1) ORDER BY activities.identifiedat DESC LIMIT 20", searchKey)
|
||
|
} else {
|
||
|
rows, err = pool.Query(context.Background(), "SELECT activities.id, activities.document, actors.document FROM activities as activities INNER JOIN actors as actors ON activities.document->>'actor' = actors.document->>'id' ORDER BY activities.identifiedat DESC LIMIT 20")
|
||
|
}
|
||
|
|
||
|
if err != nil {
|
||
|
panic(err)
|
||
|
}
|
||
|
defer rows.Close()
|
||
|
|
||
|
|
||
|
var activitiesJson []map[string]json.RawMessage
|
||
|
for rows.Next() {
|
||
|
var id int
|
||
|
var activityRaw string
|
||
|
var actorRaw string
|
||
|
var activityJson map[string]json.RawMessage
|
||
|
|
||
|
err = rows.Scan(&id, &activityRaw, &actorRaw)
|
||
|
if err != nil {
|
||
|
panic(err)
|
||
|
}
|
||
|
|
||
|
err := json.Unmarshal([]byte(activityRaw), &activityJson)
|
||
|
if err != nil {
|
||
|
fmt.Println(err)
|
||
|
}
|
||
|
|
||
|
activityJson["actor"] = json.RawMessage(actorRaw)
|
||
|
activitiesJson = append(activitiesJson, activityJson)
|
||
|
}
|
||
|
|
||
|
data, err := json.Marshal(activitiesJson)
|
||
|
if err != nil {
|
||
|
log.Fatal("error marshaling combined activity: %v", err)
|
||
|
}
|
||
|
fmt.Fprintf(w, "%s", data)
|
||
|
}
|
||
|
|
||
|
func main() {
|
||
|
getSettings()
|
||
|
pool = getDbPool()
|
||
|
|
||
|
http.HandleFunc("/search", search)
|
||
|
log.Print("Starting HTTP inbox on port 6432")
|
||
|
log.Fatal(http.ListenAndServe("0.0.0.0:6432", nil))
|
||
|
}
|