Follow the leader with help from a server
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

81 line
1.8KB

  1. // NGnius 2020-01-30
  2. package main
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "net/http"
  7. "net/url"
  8. "strconv"
  9. )
  10. func boardHandler(w http.ResponseWriter, r *http.Request) {
  11. if r.Method != "GET" {
  12. w.WriteHeader(405)
  13. return
  14. }
  15. w.Header().Add("content-type", "application/json")
  16. w.Header().Add("Access-Control-Allow-Origin", "*")
  17. args := r.URL.Query()
  18. // check args pre-conditions
  19. if !checkArgExists(args, "board", w) {
  20. return
  21. }
  22. board := args.Get("board")
  23. if !checkArgExists(args, "count", w) || !checkArgInt(args, "count", w, 0) {
  24. w.WriteHeader(400)
  25. return
  26. }
  27. count, _ := strconv.Atoi(args.Get("count"))
  28. if !checkArgExists(args, "start", w) || !checkArgInt(args, "start", w, 0) {
  29. w.WriteHeader(400)
  30. return
  31. }
  32. start, _ := strconv.Atoi(args.Get("start"))
  33. // execute query
  34. result := NewResult("", r.URL.String())
  35. b, err := boardByName(board)
  36. //b, ok := boards[board]
  37. if err != nil {
  38. fmt.Println(err)
  39. w.WriteHeader(404)
  40. return
  41. }
  42. bEntries, loadErr := b.SomeEntries(int64(start), int64(start+count))
  43. if loadErr != nil {
  44. fmt.Println(loadErr)
  45. w.WriteHeader(404)
  46. return
  47. }
  48. for _, entry := range bEntries {
  49. item, _ := entry.JsonObject()
  50. result.Items = append(result.Items, &item)
  51. }
  52. result.Query = fmt.Sprintf("load board[%s] from %d to %d", board, start, count+start)
  53. result.Complete()
  54. data, err := json.Marshal(result)
  55. if err != nil {
  56. w.WriteHeader(500)
  57. return
  58. }
  59. w.Write(data)
  60. }
  61. func checkArgExists(values url.Values, key string, w http.ResponseWriter) (ok bool) {
  62. ok = values.Get(key) != ""
  63. if !ok {
  64. w.WriteHeader(400)
  65. }
  66. return
  67. }
  68. func checkArgInt(values url.Values, key string, w http.ResponseWriter, min int) (ok bool) {
  69. intVal, err := strconv.Atoi(values.Get(key))
  70. ok = err == nil && intVal >= min
  71. if !ok {
  72. w.WriteHeader(400)
  73. }
  74. return
  75. }