|
- // 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) {
- w.WriteHeader(400)
- return
- }
- count, _ := strconv.Atoi(args.Get("count"))
- if !checkArgExists(args, "start", w) || !checkArgInt(args, "start", w, 0) {
- w.WriteHeader(400)
- return
- }
- start, _ := strconv.Atoi(args.Get("start"))
- // execute query
- result := NewResult("", r.URL.String())
- b, err := boardByName(board)
- //b, ok := boards[board]
- if err != nil {
- fmt.Println(err)
- w.WriteHeader(404)
- return
- }
- bEntries, loadErr := b.SomeEntries(int64(start), int64(start+count))
- if loadErr != nil {
- fmt.Println(loadErr)
- w.WriteHeader(404)
- return
- }
- for _, entry := range bEntries {
- item, _ := entry.JsonObject()
- 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
- }
|