api.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Package api implements REST API for sftpgo.
  2. // REST API allows to manage users and quota and to get real time reports for the active connections
  3. // with possibility of forcibly closing a connection.
  4. // The OpenAPI 3 schema for the exposed API can be found inside the source tree:
  5. // https://github.com/drakkan/sftpgo/tree/master/api/schema/openapi.yaml
  6. package api
  7. import (
  8. "net/http"
  9. "github.com/drakkan/sftpgo/dataprovider"
  10. "github.com/go-chi/chi"
  11. "github.com/go-chi/render"
  12. )
  13. const (
  14. logSender = "api"
  15. activeConnectionsPath = "/api/v1/sftp_connection"
  16. quotaScanPath = "/api/v1/quota_scan"
  17. userPath = "/api/v1/user"
  18. )
  19. var (
  20. router *chi.Mux
  21. dataProvider dataprovider.Provider
  22. )
  23. // HTTPDConf httpd daemon configuration
  24. type HTTPDConf struct {
  25. // The port used for serving HTTP requests. 0 disable the HTTP server. Default: 8080
  26. BindPort int `json:"bind_port"`
  27. // The address to listen on. A blank value means listen on all available network interfaces. Default: "127.0.0.1"
  28. BindAddress string `json:"bind_address"`
  29. }
  30. type apiResponse struct {
  31. Error string `json:"error"`
  32. Message string `json:"message"`
  33. HTTPStatus int `json:"status"`
  34. }
  35. func init() {
  36. initializeRouter()
  37. }
  38. // SetDataProvider sets the data provider to use to fetch the data about users
  39. func SetDataProvider(provider dataprovider.Provider) {
  40. dataProvider = provider
  41. }
  42. func sendAPIResponse(w http.ResponseWriter, r *http.Request, err error, message string, code int) {
  43. var errorString string
  44. if err != nil {
  45. errorString = err.Error()
  46. }
  47. resp := apiResponse{
  48. Error: errorString,
  49. Message: message,
  50. HTTPStatus: code,
  51. }
  52. if code != http.StatusOK {
  53. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  54. w.WriteHeader(code)
  55. }
  56. render.JSON(w, r, resp)
  57. }
  58. func getRespStatus(err error) int {
  59. if _, ok := err.(*dataprovider.ValidationError); ok {
  60. return http.StatusBadRequest
  61. }
  62. if _, ok := err.(*dataprovider.MethodDisabledError); ok {
  63. return http.StatusForbidden
  64. }
  65. return http.StatusInternalServerError
  66. }