api.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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/connection"
  16. quotaScanPath = "/api/v1/quota_scan"
  17. userPath = "/api/v1/user"
  18. versionPath = "/api/v1/version"
  19. )
  20. var (
  21. router *chi.Mux
  22. dataProvider dataprovider.Provider
  23. )
  24. // HTTPDConf httpd daemon configuration
  25. type HTTPDConf struct {
  26. // The port used for serving HTTP requests. 0 disable the HTTP server. Default: 8080
  27. BindPort int `json:"bind_port" mapstructure:"bind_port"`
  28. // The address to listen on. A blank value means listen on all available network interfaces. Default: "127.0.0.1"
  29. BindAddress string `json:"bind_address" mapstructure:"bind_address"`
  30. }
  31. type apiResponse struct {
  32. Error string `json:"error"`
  33. Message string `json:"message"`
  34. HTTPStatus int `json:"status"`
  35. }
  36. func init() {
  37. initializeRouter()
  38. }
  39. // SetDataProvider sets the data provider to use to fetch the data about users
  40. func SetDataProvider(provider dataprovider.Provider) {
  41. dataProvider = provider
  42. }
  43. func sendAPIResponse(w http.ResponseWriter, r *http.Request, err error, message string, code int) {
  44. var errorString string
  45. if err != nil {
  46. errorString = err.Error()
  47. }
  48. resp := apiResponse{
  49. Error: errorString,
  50. Message: message,
  51. HTTPStatus: code,
  52. }
  53. if code != http.StatusOK {
  54. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  55. w.WriteHeader(code)
  56. }
  57. render.JSON(w, r, resp)
  58. }
  59. func getRespStatus(err error) int {
  60. if _, ok := err.(*dataprovider.ValidationError); ok {
  61. return http.StatusBadRequest
  62. }
  63. if _, ok := err.(*dataprovider.MethodDisabledError); ok {
  64. return http.StatusForbidden
  65. }
  66. return http.StatusInternalServerError
  67. }