1 Star 0 Fork 0

fpy-go/plugin

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
store.go 1.99 KB
一键复制 编辑 原始数据 按行查看 历史
晴空 提交于 2024-01-22 10:23 +08:00 . first commit
package api
import (
"crypto/sha1"
"encoding/hex"
"io"
"net/http"
"os"
"path"
"github.com/gorilla/mux"
"go.uber.org/zap"
)
// Store godoc
// @Summary Upload file
// @Description writes the posted content to disk at /data/hash and returns the SHA1 hash of the content
// @Tags HTTP API
// @Accept json
// @Produce json
// @Router /store [post]
// @Success 200 {object} api.MapResponse
func (s *Server) storeWriteHandler(w http.ResponseWriter, r *http.Request) {
_, span := s.tracer.Start(r.Context(), "storeWriteHandler")
defer span.End()
body, err := io.ReadAll(r.Body)
if err != nil {
s.ErrorResponse(w, r, span, "reading the request body failed", http.StatusBadRequest)
return
}
hash := hash(string(body))
err = os.WriteFile(path.Join(s.config.DataPath, hash), body, 0644)
if err != nil {
s.logger.Warn("writing file failed", zap.Error(err), zap.String("file", path.Join(s.config.DataPath, hash)))
s.ErrorResponse(w, r, span, "writing file failed", http.StatusInternalServerError)
return
}
s.JSONResponseCode(w, r, map[string]string{"hash": hash}, http.StatusAccepted)
}
// Store godoc
// @Summary Download file
// @Description returns the content of the file /data/hash if exists
// @Tags HTTP API
// @Accept json
// @Produce plain
// @Param hash path string true "hash value"
// @Router /store/{hash} [get]
// @Success 200 {string} string "file"
func (s *Server) storeReadHandler(w http.ResponseWriter, r *http.Request) {
_, span := s.tracer.Start(r.Context(), "storeReadHandler")
defer span.End()
hash := mux.Vars(r)["hash"]
content, err := os.ReadFile(path.Join(s.config.DataPath, hash))
if err != nil {
s.logger.Warn("reading file failed", zap.Error(err), zap.String("file", path.Join(s.config.DataPath, hash)))
s.ErrorResponse(w, r, span, "reading file failed", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusAccepted)
w.Write([]byte(content))
}
func hash(input string) string {
h := sha1.New()
h.Write([]byte(input))
return hex.EncodeToString(h.Sum(nil))
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/fpy-go/plugin.git
git@gitee.com:fpy-go/plugin.git
fpy-go
plugin
plugin
345896415f40

搜索帮助