rest.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. * EliasDB
  3. *
  4. * Copyright 2016 Matthias Ladkau. All rights reserved.
  5. *
  6. * This Source Code Form is subject to the terms of the Mozilla Public
  7. * License, v. 2.0. If a copy of the MPL was not distributed with this
  8. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  9. */
  10. package v1
  11. import (
  12. "net/http"
  13. "strconv"
  14. "strings"
  15. "devt.de/krotik/eliasdb/api"
  16. )
  17. /*
  18. APIv1 is the directory for version 1 of the API
  19. */
  20. const APIv1 = "/v1"
  21. /*
  22. HTTPHeaderTotalCount is a special header value containing the total count of objects.
  23. */
  24. const HTTPHeaderTotalCount = "X-Total-Count"
  25. /*
  26. HTTPHeaderCacheID is a special header value containing a cache ID for a quick follow up query.
  27. */
  28. const HTTPHeaderCacheID = "X-Cache-Id"
  29. /*
  30. V1EndpointMap is a map of urls to endpoints for version 1 of the API
  31. */
  32. var V1EndpointMap = map[string]api.RestEndpointInst{
  33. EndpointBlob: BlobEndpointInst,
  34. EndpointClusterQuery: ClusterEndpointInst,
  35. EndpointEql: EqlEndpointInst,
  36. EndpointGraph: GraphEndpointInst,
  37. EndpointGraphQL: GraphQLEndpointInst,
  38. EndpointGraphQLQuery: GraphQLQueryEndpointInst,
  39. EndpointGraphQLSubscriptions: GraphQLSubscriptionsEndpointInst,
  40. EndpointIndexQuery: IndexEndpointInst,
  41. EndpointFindQuery: FindEndpointInst,
  42. EndpointInfoQuery: InfoEndpointInst,
  43. EndpointQuery: QueryEndpointInst,
  44. EndpointQueryResult: QueryResultEndpointInst,
  45. }
  46. // Helper functions
  47. // ================
  48. /*
  49. checkResources check given resources for a GET request.
  50. */
  51. func checkResources(w http.ResponseWriter, resources []string, requiredMin int, requiredMax int, errorMsg string) bool {
  52. if len(resources) < requiredMin {
  53. http.Error(w, errorMsg, http.StatusBadRequest)
  54. return false
  55. } else if len(resources) > requiredMax {
  56. http.Error(w, "Invalid resource specification: "+strings.Join(resources[1:], "/"), http.StatusBadRequest)
  57. return false
  58. }
  59. return true
  60. }
  61. /*
  62. Extract a positive number from a query parameter. Returns -1 and true
  63. if the parameter was not given.
  64. */
  65. func queryParamPosNum(w http.ResponseWriter, r *http.Request, param string) (int, bool) {
  66. val := r.URL.Query().Get(param)
  67. if val == "" {
  68. return -1, true
  69. }
  70. num, err := strconv.Atoi(val)
  71. if err != nil || num < 0 {
  72. http.Error(w, "Invalid parameter value: "+param+" should be a positive integer number", http.StatusBadRequest)
  73. return -1, false
  74. }
  75. return num, true
  76. }