X-Git-Url: http://jaekl.net/gitweb/?p=quanweb.git;a=blobdiff_plain;f=main%2Fhandler.go;fp=main%2Fhandler.go;h=52d08e5f8ff98f192f9dbc109418424522ac6719;hp=0000000000000000000000000000000000000000;hb=d4b5c2903e7b0c2267aa7bfdef514a3d1e447de3;hpb=0a720941a76c7b9c7fa3303c6fb75c5d39c95919 diff --git a/main/handler.go b/main/handler.go new file mode 100644 index 0000000..52d08e5 --- /dev/null +++ b/main/handler.go @@ -0,0 +1,97 @@ +package main + +import ( + "encoding/json" + "fmt" + "net/http" + "strconv" + "strings" +) + +const PARAM_IDS = "ids" +const MAX_TERMS = 10 + +// ============================================================================ +func handler(w http.ResponseWriter, r *http.Request) { + err := r.ParseForm() + if nil != err { + fmt.Fprintln(w, "ERROR!", err) + return + } + + action := r.URL.Path[1:] + + switch(action) { + case "info": + handleInfo(w, r) + case "search": + handleSearch(w, r) + default: + fmt.Fprintf(w, "Unrecognized request: %s\n", r.URL.Path[1:]) + fmt.Fprintf(w, "id: %s\n", r.FormValue("id")) + + fmt.Fprintln(w, "URL: ", r.URL) + fmt.Fprintln(w, "Query: ", r.URL.Query()) + } +} + +func handleInfo(w http.ResponseWriter, r *http.Request) { + idParams := r.Form[PARAM_IDS] + if 1 != len(idParams) { + fmt.Fprintln(w, "ERROR! Detected either zero or multiple ids= parameters. Exactly one expected.") + return + } + + idParam := idParams[0] + idStrings := strings.Split(idParam, ",") + ids := make([]int, len(idStrings)) + for i, v := range(idStrings) { + var err error + ids[i], err = strconv.Atoi(v) + if nil != err { + ids[i] = 0 + } + } + + books := queryBooksByIds(ids) + + var jsonValue []byte + var err error + jsonValue, err = json.Marshal(books) + if nil != err { + fmt.Fprintln(w, "ERROR!", err) + } else { + w.Write(jsonValue) + } +} + +func handleSearch(w http.ResponseWriter, r *http.Request) { + fields := []Field{Author, Title, Series} + + terms := make([]SearchTerm, len(fields)) + + count := 0 + for _, fv := range(fields) { + paramName := fv.String() + paramValues := r.Form[paramName] + for _, pv := range(paramValues) { + if count >= len(terms) { + fmt.Printf("WARNING: limit of %v search terms exceeded. One or more terms ignored.") + break + } + terms[count] = SearchTerm{Attribute:fv, Text:pv} + count++ + } + } + + terms = terms[:count] + + ids := queryIds(terms) + + jsonValue, err := json.Marshal(ids) + if nil != err { + fmt.Fprintln(w, "ERROR!", err) + } else { + w.Write(jsonValue) + } +}