61 lines
1.4 KiB
Go
61 lines
1.4 KiB
Go
package api
|
|
|
|
import (
|
|
"TheAdversary/database"
|
|
"encoding/json"
|
|
"net/http"
|
|
"strconv"
|
|
"time"
|
|
)
|
|
|
|
func Search(w http.ResponseWriter, r *http.Request) {
|
|
var err error
|
|
var q string
|
|
var from, to time.Time
|
|
var limit int64
|
|
|
|
query := r.URL.Query()
|
|
q = query.Get("q")
|
|
if f := query.Get("from"); f != "" {
|
|
from, err = time.Parse(time.RFC3339, f)
|
|
if err != nil {
|
|
ApiError{"could not parse 'from' parameter as RFC3339 time", http.StatusUnprocessableEntity}.Send(w)
|
|
return
|
|
}
|
|
}
|
|
if t := query.Get("to"); t != "" {
|
|
to, err = time.Parse(time.RFC3339, t)
|
|
if err != nil {
|
|
ApiError{"could not parse 'to' parameter as RFC3339 time", http.StatusUnprocessableEntity}.Send(w)
|
|
return
|
|
}
|
|
}
|
|
if l := query.Get("limit"); l != "" {
|
|
limit, err = strconv.ParseInt(l, 10, 64)
|
|
if err != nil {
|
|
ApiError{"invalid 'limit' parameter", http.StatusUnprocessableEntity}.Send(w)
|
|
return
|
|
}
|
|
} else {
|
|
limit = 20
|
|
}
|
|
|
|
articles, err := database.GetDB().GetArticles(q, database.ArticleQueryOptions{
|
|
Title: true,
|
|
Summary: true,
|
|
From: from.Unix(),
|
|
To: to.Unix(),
|
|
Limit: int(limit),
|
|
})
|
|
|
|
var articleSummaries []database.ArticleSummary
|
|
for _, article := range articles {
|
|
articleSummaries = append(articleSummaries, article.ToArticleSummary())
|
|
}
|
|
|
|
w.WriteHeader(http.StatusOK)
|
|
json.NewEncoder(w).Encode(struct {
|
|
Articles []database.ArticleSummary `json:"articles"`
|
|
}{articleSummaries})
|
|
}
|