-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch.go
More file actions
55 lines (43 loc) · 1.16 KB
/
Copy pathsearch.go
File metadata and controls
55 lines (43 loc) · 1.16 KB
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
package main
import (
"encoding/json"
"io"
"net/http"
"github.com/gorilla/mux"
)
type SearchService struct {
store Store
}
func NewSearchService(s *Store) *SearchService {
return &SearchService{store: *s}
}
func (s *SearchService) RegisterRouters(r *mux.Router) {
r.HandleFunc("/search/", WithJWTAuth(s.handleSearchUser, s.store)).Methods("POST")
}
func (s *SearchService) handleSearchUser(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Error reading request body", http.StatusBadRequest)
return
}
defer r.Body.Close()
var payload map[string]interface{}
err = json.Unmarshal(body, &payload)
if err != nil {
http.Error(w, "Error unmarshaling JSON", http.StatusBadRequest)
return
}
if payload["native"] == nil || payload["learning"] == nil {
http.Error(w, "JSON Data is invalid", http.StatusBadRequest)
return
}
users, err := s.store.SearchUser(payload["native"].(string), payload["learning"].(string))
if err != nil {
http.Error(w, "MySQL Error", http.StatusBadRequest)
return
}
response := map[string]interface{}{
"searchedUsers": users,
}
WriteJSON(w, http.StatusOK, response)
}