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.

handlers.go 1.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. return
  25. }
  26. count, _ := strconv.Atoi(args.Get("count"))
  27. if !checkArgExists(args, "start", w) || !checkArgInt(args, "start", w, 0) {
  28. return
  29. }
  30. start, _ := strconv.Atoi(args.Get("start"))
  31. // execute query
  32. result := NewResult("", r.URL.String())
  33. b, ok := boards[board]
  34. if !ok {
  35. w.WriteHeader(404)
  36. return
  37. }
  38. if len(b.Entries) < start+count {
  39. count = len(b.Entries) - start
  40. }
  41. // result.Items = b.Entries[start : start+count]
  42. for _, entry := range b.Entries[start : start+count] {
  43. item := entry
  44. result.Items = append(result.Items, &item)
  45. }
  46. result.Query = fmt.Sprintf("load board[%s] from %d to %d", board, start, count+start)
  47. result.Complete()
  48. data, err := json.Marshal(result)
  49. if err != nil {
  50. w.WriteHeader(500)
  51. return
  52. }
  53. w.Write(data)
  54. }
  55. func checkArgExists(values url.Values, key string, w http.ResponseWriter) (ok bool) {
  56. ok = values.Get(key) != ""
  57. if !ok {
  58. w.WriteHeader(400)
  59. }
  60. return
  61. }
  62. func checkArgInt(values url.Values, key string, w http.ResponseWriter, min int) (ok bool) {
  63. intVal, err := strconv.Atoi(values.Get(key))
  64. ok = err == nil && intVal >= min
  65. if !ok {
  66. w.WriteHeader(400)
  67. }
  68. return
  69. }