// NGnius 2020-01-30 package main import ( "encoding/json" "fmt" "net/http" "net/url" "strconv" ) func boardHandler(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" { w.WriteHeader(405) return } w.Header().Add("content-type", "application/json") w.Header().Add("Access-Control-Allow-Origin", "*") args := r.URL.Query() // check args pre-conditions if !checkArgExists(args, "board", w) { return } board := args.Get("board") if !checkArgExists(args, "count", w) || !checkArgInt(args, "count", w, 0) { return } count, _ := strconv.Atoi(args.Get("count")) if !checkArgExists(args, "start", w) || !checkArgInt(args, "start", w, 0) { return } start, _ := strconv.Atoi(args.Get("start")) // execute query result := NewResult("", r.URL.String()) b, ok := boards[board] if !ok { w.WriteHeader(404) return } if len(b.Entries) < start+count { count = len(b.Entries) - start } // result.Items = b.Entries[start : start+count] for _, entry := range b.Entries[start : start+count] { item := entry result.Items = append(result.Items, &item) } result.Query = fmt.Sprintf("load board[%s] from %d to %d", board, start, count+start) result.Complete() data, err := json.Marshal(result) if err != nil { w.WriteHeader(500) return } w.Write(data) } func checkArgExists(values url.Values, key string, w http.ResponseWriter) (ok bool) { ok = values.Get(key) != "" if !ok { w.WriteHeader(400) } return } func checkArgInt(values url.Values, key string, w http.ResponseWriter, min int) (ok bool) { intVal, err := strconv.Atoi(values.Get(key)) ok = err == nil && intVal >= min if !ok { w.WriteHeader(400) } return }