filesapi.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package api
  2. import (
  3. "bufio"
  4. "fmt"
  5. "net/http"
  6. "github.com/go-chi/chi"
  7. "github.com/go-chi/render"
  8. "wkla.no-ip.biz/gogs/Willie/MsgService/MessageService/dao"
  9. )
  10. //FilesRoutes getting all routes for the config endpoint
  11. func FilesRoutes() *chi.Mux {
  12. router := chi.NewRouter()
  13. router.With(RoleCheck([]string{"edit", "read"})).Get("/{bename}/{fileId}", GetFileHandler)
  14. router.With(RoleCheck([]string{"edit"})).Post("/{bename}/", PostFileEndpoint)
  15. return router
  16. }
  17. // GetFileHandler get a file
  18. func GetFileHandler(response http.ResponseWriter, request *http.Request) {
  19. backend := chi.URLParam(request, "bename")
  20. fileID := chi.URLParam(request, "fileId")
  21. log.Infof("GET: path: %s, be: %s, fileID: %s", request.URL.Path, backend, fileID)
  22. filename, err := dao.GetStorage().GetFilename(backend, fileID)
  23. if filename == "" {
  24. render.Render(response, request, ErrNotFound)
  25. return
  26. }
  27. response.Header().Add("Content-disposition", "attachment; filename=\""+filename+"\"")
  28. err = dao.GetStorage().GetFile(backend, fileID, response)
  29. if err != nil {
  30. render.Render(response, request, ErrInvalidRequest(err))
  31. return
  32. }
  33. }
  34. //PostFileEndpoint create a new file, return the id
  35. func PostFileEndpoint(response http.ResponseWriter, request *http.Request) {
  36. backend := chi.URLParam(request, "bename")
  37. log.Infof("POST: path: %s, be: %s", request.URL.Path, backend)
  38. request.ParseForm()
  39. f, fileHeader, err := request.FormFile("file")
  40. if err != nil {
  41. render.Render(response, request, ErrInvalidRequest(err))
  42. return
  43. }
  44. //mimeType := fileHeader.Header.Get("Content-type")
  45. filename := fileHeader.Filename
  46. reader := bufio.NewReader(f)
  47. fileid, err := dao.GetStorage().AddFile(backend, filename, reader)
  48. if err != nil {
  49. render.Render(response, request, ErrInvalidRequest(err))
  50. return
  51. }
  52. log.Infof("fileid: %s", fileid)
  53. location := fmt.Sprintf("/api/v1/files/%s/%s", backend, fileid)
  54. response.Header().Add("Location", location)
  55. render.Status(request, http.StatusCreated)
  56. m := make(map[string]interface{})
  57. m["fileid"] = fileid
  58. m["filename"] = filename
  59. render.JSON(response, request, m)
  60. }