-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathweb.go
262 lines (225 loc) · 6.76 KB
/
web.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
// Copyright (C) 2024-2025 by Ubaldo Porcheddu <ubaldo@eja.it>
package main
import (
"encoding/json"
"fmt"
"html/template"
"io/fs"
"log"
"net/http"
"os"
"strconv"
)
type APIRequest struct {
Query string `json:"query,omitempty"`
Limit int `json:"limit,omitempty"`
ID int `json:"id,omitempty"`
}
type APIResponse struct {
Status string `json:"status"`
Message string `json:"message,omitempty"`
Results []SearchResult `json:"results,omitempty"`
Article []ArticleResult `json:"article,omitempty"`
}
type WebServer struct {
template *template.Template
}
func NewWebServer() (*WebServer, error) {
tmpl, err := template.ParseFS(assets, "assets/templates/*")
if err != nil {
return nil, fmt.Errorf("error parsing templates: %v", err)
}
return &WebServer{
template: tmpl,
}, nil
}
func (s *WebServer) executeTemplate(w http.ResponseWriter, templateName string, data interface{}) {
err := s.template.ExecuteTemplate(w, templateName, data)
if err != nil {
http.Error(w, fmt.Sprintf("error executing template: %v", err), http.StatusInternalServerError)
return
}
}
func (s *WebServer) handleHTMLSearch(w http.ResponseWriter, r *http.Request) {
type TemplateData struct {
Query string
Results []SearchResult
HasQuery bool
Language string
}
if r.Method == "POST" {
query := r.FormValue("query")
results, err := Search(query, options.limit)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
data := TemplateData{
Query: query,
Results: results,
HasQuery: query != "",
Language: options.language,
}
log.Println(data)
s.executeTemplate(w, "search.html", data)
return
}
data := TemplateData{
Language: options.language,
}
s.executeTemplate(w, "search.html", data)
}
func (s *WebServer) handleHTMLArticle(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
value := r.FormValue("id")
id, err := strconv.Atoi(value)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
results, err := db.ArticleGet(id)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
data := struct {
Language string
Results []ArticleResult
}{
Language: options.language,
Results: results,
}
s.executeTemplate(w, "article.html", data)
}
}
func (s *WebServer) sendAPIError(w http.ResponseWriter, message string, statusCode int) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
json.NewEncoder(w).Encode(APIResponse{
Status: "error",
Message: message,
})
}
func (s *WebServer) handleGenericAPISearch(w http.ResponseWriter, r *http.Request, searchFunc func(query string, limit int) ([]SearchResult, error), searchType string) {
w.Header().Set("Content-Type", "application/json")
var request APIRequest
var query string
var limit int = options.limit
var err error
if r.Method == "POST" {
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
s.sendAPIError(w, "Invalid JSON request", http.StatusBadRequest)
return
}
query = request.Query
if request.Limit > 0 {
limit = request.Limit
}
} else {
query = r.URL.Query().Get("query")
if limitStr := r.URL.Query().Get("limit"); limitStr != "" {
limit, err = strconv.Atoi(limitStr)
if err != nil {
s.sendAPIError(w, "Invalid limit parameter", http.StatusBadRequest)
return
}
}
}
log.Printf("API %s search %s: %s", r.Method, searchType, query)
if query == "" {
s.sendAPIError(w, "Query parameter is required", http.StatusBadRequest)
return
}
results, err := searchFunc(query, limit)
if err != nil {
s.sendAPIError(w, fmt.Sprintf("%s search error: %v", searchType, err), http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(APIResponse{
Status: "success",
Results: results,
})
}
func (s *WebServer) handleAPISearch(w http.ResponseWriter, r *http.Request) {
s.handleGenericAPISearch(w, r, Search, "Search")
}
func (s *WebServer) handleAPISearchTitle(w http.ResponseWriter, r *http.Request) {
s.handleGenericAPISearch(w, r, db.SearchTitle, "Title")
}
func (s *WebServer) handleAPISearchContent(w http.ResponseWriter, r *http.Request) {
s.handleGenericAPISearch(w, r, db.SearchContent, "Content")
}
func (s *WebServer) handleAPISearchVectors(w http.ResponseWriter, r *http.Request) {
if !ai {
s.sendAPIError(w, "Vector search is not enabled", http.StatusBadRequest)
return
}
s.handleGenericAPISearch(w, r, db.SearchVectors, "Vector")
}
func (s *WebServer) handleAPIArticle(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var request APIRequest
var id int
var err error
if r.Method == "POST" {
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
s.sendAPIError(w, "Invalid JSON request", http.StatusBadRequest)
return
}
id = request.ID
} else {
idStr := r.URL.Query().Get("id")
if idStr == "" {
s.sendAPIError(w, "ID parameter is required", http.StatusBadRequest)
return
}
id, err = strconv.Atoi(idStr)
if err != nil {
s.sendAPIError(w, "Invalid ID parameter", http.StatusBadRequest)
return
}
}
log.Printf("API %s article: %d", r.Method, id)
article, err := db.ArticleGet(id)
if err != nil {
s.sendAPIError(w, fmt.Sprintf("Error retrieving article: %v", err), http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(APIResponse{
Status: "success",
Article: article,
})
}
func (s *WebServer) Start(host string, port int) error {
http.HandleFunc("/", s.handleHTMLSearch)
http.HandleFunc("/article", s.handleHTMLArticle)
http.HandleFunc("/api/search", s.handleAPISearch)
http.HandleFunc("/api/search/title", s.handleAPISearchTitle)
http.HandleFunc("/api/search/content", s.handleAPISearchContent)
http.HandleFunc("/api/search/vectors", s.handleAPISearchVectors)
http.HandleFunc("/api/article", s.handleAPIArticle)
subFS, err := fs.Sub(assets, "assets/static")
if err != nil {
panic(fmt.Errorf("failed to access embedded subdirectory: %w", err))
}
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.FS(subFS))))
address := fmt.Sprintf("%s:%d", host, port)
if options.webTlsPrivate != "" && options.webTlsPublic != "" {
if _, err := os.Stat(options.webTlsPrivate); err != nil {
return fmt.Errorf("failed to open private certificate")
} else if _, err := os.Stat(options.webTlsPublic); err != nil {
return fmt.Errorf("failed to open public certificate")
} else {
log.Println("Starting server on https://" + address)
if err := http.ListenAndServeTLS(address, options.webTlsPublic, options.webTlsPrivate, nil); err != nil {
return err
}
}
} else {
log.Println("Starting server on http://" + address)
if err := http.ListenAndServe(address, nil); err != nil {
return err
}
}
return nil
}