encodable a good

Former-commit-id: a0afebd82dfd256ec70c02c607af2a9b3b4b046f
This commit is contained in:
bel
2019-06-22 08:58:54 -06:00
parent 730cf1e15a
commit be065c5dcb
12 changed files with 260 additions and 86 deletions

View File

@@ -2,13 +2,11 @@ package server
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"local/router"
"local/rssmon3/config"
"local/sandbox/selenium/copart/copart/auction"
"local/storage"
"log"
"net/http"
@@ -68,11 +66,7 @@ func (s *Server) auctions(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
switch strings.ToLower(r.Method) {
case "get":
if len(r.Form) > 0 {
foo = s.query
} else {
foo = s.get
}
foo = s.get
}
foo(w, r)
}
@@ -96,70 +90,3 @@ func (s *Server) get(w http.ResponseWriter, r *http.Request) {
}
io.Copy(w, bytes.NewBuffer(value))
}
func (s *Server) query(w http.ResponseWriter, r *http.Request) {
log.Println("QUERY", r.URL.Path)
list, err := s.list()
if err != nil {
s.error(w, r, err)
return
}
form := r.Form
for _, value := range form {
for _, chunk := range value {
iteration := []string{}
for _, name := range list {
if strings.Contains(strings.ToLower(name), strings.ToLower(chunk)) {
iteration = append(iteration, name)
}
}
list = iteration
}
}
if len(list) < 1 {
s.notFound(w, r)
return
}
carsJSON, err := s.gatherCarsTruncatedJSON(list)
if err != nil {
s.error(w, r, fmt.Errorf("gather cars(%v): %v", list, err))
return
}
w.Write(carsJSON)
}
func (s *Server) list() ([]string, error) {
db := config.Values().DB
list := []string{}
if b, err := db.Get("LIST"); err == storage.ErrNotFound {
list = []string{}
db.Set("LIST", []byte("[]"))
} else if err != nil {
return nil, fmt.Errorf("bad list in storage: %v", err)
} else if err := json.Unmarshal(b, &list); err != nil {
return nil, fmt.Errorf("bad list in storage: %v", err)
}
return list, nil
}
func (s *Server) gatherCarsTruncatedJSON(keys []string) ([]byte, error) {
cars := []*auction.Car{}
k := 0
for _, key := range keys {
k += 1
if k > 50 {
cars = append(cars, &auction.Car{Title: "Max results reached, please search more specifically"})
break
}
b, err := config.Values().DB.Get(key)
if err != nil {
return nil, err
}
c := auction.NewCar()
if err := c.Decode(b); err != nil {
return nil, err
}
cars = append(cars, c)
}
return json.Marshal(cars)
}