12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- package api
- import (
- "bufio"
- "fmt"
- "net/http"
- "github.com/go-chi/chi"
- "github.com/go-chi/render"
- "wkla.no-ip.biz/gogs/Willie/MsgService/MessageService/dao"
- )
- //FilesRoutes getting all routes for the config endpoint
- func FilesRoutes() *chi.Mux {
- router := chi.NewRouter()
- router.With(RoleCheck([]string{"edit", "read"})).Get("/{bename}/{fileId}", GetFileHandler)
- router.With(RoleCheck([]string{"edit"})).Post("/{bename}/", PostFileEndpoint)
- return router
- }
- // GetFileHandler get a file
- func GetFileHandler(response http.ResponseWriter, request *http.Request) {
- backend := chi.URLParam(request, "bename")
- fileID := chi.URLParam(request, "fileId")
- log.Infof("GET: path: %s, be: %s, fileID: %s", request.URL.Path, backend, fileID)
- filename, err := dao.GetStorage().GetFilename(backend, fileID)
- if filename == "" {
- render.Render(response, request, ErrNotFound)
- return
- }
- response.Header().Add("Content-disposition", "attachment; filename=\""+filename+"\"")
- err = dao.GetStorage().GetFile(backend, fileID, response)
- if err != nil {
- render.Render(response, request, ErrInvalidRequest(err))
- return
- }
- }
- //PostFileEndpoint create a new file, return the id
- func PostFileEndpoint(response http.ResponseWriter, request *http.Request) {
- backend := chi.URLParam(request, "bename")
- log.Infof("POST: path: %s, be: %s", request.URL.Path, backend)
- request.ParseForm()
- f, fileHeader, err := request.FormFile("file")
- if err != nil {
- render.Render(response, request, ErrInvalidRequest(err))
- return
- }
- //mimeType := fileHeader.Header.Get("Content-type")
- filename := fileHeader.Filename
- reader := bufio.NewReader(f)
- fileid, err := dao.GetStorage().AddFile(backend, filename, reader)
- if err != nil {
- render.Render(response, request, ErrInvalidRequest(err))
- return
- }
- log.Infof("fileid: %s", fileid)
- location := fmt.Sprintf("/api/v1/files/%s/%s", backend, fileid)
- response.Header().Add("Location", location)
- render.Status(request, http.StatusCreated)
- m := make(map[string]interface{})
- m["fileid"] = fileid
- m["filename"] = filename
- render.JSON(response, request, m)
- }
|