api.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package api
  2. import (
  3. "net/http"
  4. "github.com/drakkan/sftpgo/dataprovider"
  5. "github.com/go-chi/chi"
  6. "github.com/go-chi/render"
  7. )
  8. const (
  9. logSender = "api"
  10. activeConnectionsPath = "/api/v1/sftp_connection"
  11. quotaScanPath = "/api/v1/quota_scan"
  12. userPath = "/api/v1/user"
  13. )
  14. var (
  15. router *chi.Mux
  16. dataProvider dataprovider.Provider
  17. )
  18. // HTTPDConf httpd daemon configuration
  19. type HTTPDConf struct {
  20. BindPort int `json:"bind_port"`
  21. BindAddress string `json:"bind_address"`
  22. }
  23. type apiResponse struct {
  24. Error string `json:"error"`
  25. Message string `json:"message"`
  26. HTTPStatus int `json:"status"`
  27. }
  28. func init() {
  29. initializeRouter()
  30. }
  31. // SetDataProvider sets the data provider
  32. func SetDataProvider(provider dataprovider.Provider) {
  33. dataProvider = provider
  34. }
  35. func sendAPIResponse(w http.ResponseWriter, r *http.Request, err error, message string, code int) {
  36. var errorString string
  37. if err != nil {
  38. errorString = err.Error()
  39. }
  40. resp := apiResponse{
  41. Error: errorString,
  42. Message: message,
  43. HTTPStatus: code,
  44. }
  45. if code != http.StatusOK {
  46. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  47. w.WriteHeader(code)
  48. }
  49. render.JSON(w, r, resp)
  50. }
  51. func getRespStatus(err error) int {
  52. if _, ok := err.(*dataprovider.ValidationError); ok {
  53. return http.StatusBadRequest
  54. }
  55. if _, ok := err.(*dataprovider.MethodDisabledError); ok {
  56. return http.StatusForbidden
  57. }
  58. return http.StatusInternalServerError
  59. }