This repository has been archived by the owner on Dec 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hamming_query.go
75 lines (62 loc) · 1.6 KB
/
hamming_query.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
package sequences
import (
"database/sql"
"encoding/json"
"log"
"net/http"
"github.com/thisguycodes/dyno/hamming"
)
type HammingQuery struct {
DB *sql.DB
MaxDistance int
}
func (hq HammingQuery) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
ctx := r.Context()
// POST or GET request only
switch r.Method {
case http.MethodPost:
case http.MethodGet:
break
default:
rw.WriteHeader(http.StatusBadRequest)
return
}
incommingSequence := r.FormValue("sequence")
// empty sequence, or no sequence provided
if incommingSequence == "" {
rw.WriteHeader(http.StatusBadRequest)
return
}
// query all existing sequences
rows, err := hq.DB.QueryContext(ctx, `
SELECT UUID, description, sequence FROM sequences
`)
if err != nil {
log.Printf("Error querying for existing sequences: %q", err)
}
defer rows.Close()
matches := make([]Sequence, 0)
for rows.Next() {
sequence := Sequence{}
if err := rows.Scan(&sequence.UUID, &sequence.Description, &sequence.Sequence); err != nil {
log.Printf("Error scanning existing sequences: %q", err)
rw.WriteHeader(http.StatusInternalServerError)
return
}
if hamming.Distance(sequence.Sequence, []byte(incommingSequence)) <= hq.MaxDistance {
matches = append(matches, sequence)
}
}
if err := rows.Err(); err != nil {
log.Printf("Error calling .Next() on querying for existing sequences: %q", err)
rw.WriteHeader(http.StatusInternalServerError)
return
}
if len(matches) == 0 {
rw.WriteHeader(http.StatusNotFound)
} else {
rw.WriteHeader(http.StatusOK)
}
encoder := json.NewEncoder(rw)
encoder.Encode(matches)
}