filesapi.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. "github.com/willie68/schematic-service-go/dao"
  9. )
  10. //SchematicsRoutes getting all routes for the config endpoint
  11. func FilesRoutes() *chi.Mux {
  12. router := chi.NewRouter()
  13. router.Get("/{fileId}", GetFileHandler)
  14. router.Post("/", PostFileEndpoint)
  15. return router
  16. }
  17. // GetSchematicFileHandler gets a tenant
  18. func GetFileHandler(response http.ResponseWriter, req *http.Request) {
  19. fileID := chi.URLParam(req, "fileId")
  20. filename, err := dao.GetStorage().GetFilename(fileID)
  21. response.Header().Add("Content-disposition", "attachment; filename=\""+filename+"\"")
  22. err = dao.GetStorage().GetFile(fileID, response)
  23. if err != nil {
  24. Msg(response, http.StatusBadRequest, err.Error())
  25. return
  26. }
  27. }
  28. //PostFileEndpoint create a new file, return the id
  29. func PostFileEndpoint(response http.ResponseWriter, req *http.Request) {
  30. req.ParseForm()
  31. f, fileHeader, err := req.FormFile("file")
  32. if err != nil {
  33. Msg(response, http.StatusBadRequest, err.Error())
  34. return
  35. }
  36. //mimeType := fileHeader.Header.Get("Content-type")
  37. filename := fileHeader.Filename
  38. reader := bufio.NewReader(f)
  39. fileid, err := dao.GetStorage().AddFile(filename, reader)
  40. if err != nil {
  41. fmt.Printf("%v\n", err)
  42. } else {
  43. fmt.Printf("fileid: %s\n", fileid)
  44. }
  45. location := fmt.Sprintf("/api/v1/files/%s", fileid)
  46. response.Header().Add("Location", location)
  47. render.Status(req, http.StatusCreated)
  48. m := make(map[string]interface{})
  49. m["fileid"] = fileid
  50. m["filename"] = filename
  51. render.JSON(response, req, m)
  52. }