81 lines
1.9 KiB
Go
81 lines
1.9 KiB
Go
package api
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"gitea.konchin.com/go2025/backend/middlewares"
|
|
"gitea.konchin.com/go2025/backend/models"
|
|
"gitea.konchin.com/go2025/backend/types"
|
|
"github.com/uptrace/bunrouter"
|
|
)
|
|
|
|
type postImageOutput struct {
|
|
Id int64 `json:"id"`
|
|
Extension string `json:"extension"`
|
|
Uploader string `json:"uploadedUserId"`
|
|
UploadTS time.Time `json:"uploadedAt"`
|
|
}
|
|
|
|
// PostImage
|
|
//
|
|
// @param userinfo header string true "userinfo from /auth/gen-login-url"
|
|
// @accept image/png
|
|
// @accept image/jpeg
|
|
// @accept image/gif
|
|
// @success 200 {object} postImageOutput
|
|
// @failure 401
|
|
// @router /api/image [post]
|
|
func (self *Handlers) PostImage(
|
|
w http.ResponseWriter, req bunrouter.Request,
|
|
) error {
|
|
ctx := req.Context()
|
|
|
|
claim, ok := ctx.Value(types.AccessToken("")).(models.AccessTokenClaim)
|
|
if !ok {
|
|
return middlewares.HTTPError{
|
|
StatusCode: http.StatusUnauthorized,
|
|
Message: "missing access token",
|
|
}
|
|
}
|
|
|
|
typeHeader := strings.Split(req.Header.Get("Content-Type"), "/")
|
|
if len(typeHeader) != 2 || typeHeader[0] != "image" {
|
|
return middlewares.HTTPError{
|
|
StatusCode: http.StatusBadRequest,
|
|
Message: "incorrect 'Content-Type' header",
|
|
}
|
|
}
|
|
|
|
image := models.Image{
|
|
Extension: typeHeader[1],
|
|
Uploader: claim.UserId,
|
|
UploadTS: time.Now(),
|
|
}
|
|
err := self.db.InsertImage(ctx, &image)
|
|
if err != nil {
|
|
return middlewares.HTTPError{
|
|
StatusCode: http.StatusInternalServerError,
|
|
Message: "failed to insert image to db",
|
|
OriginError: err,
|
|
}
|
|
}
|
|
|
|
err = self.s3.PutImage(ctx,
|
|
image.Filename(), req.Body, req.ContentLength)
|
|
if err != nil {
|
|
return middlewares.HTTPError{
|
|
StatusCode: http.StatusInternalServerError,
|
|
Message: "failed to put image to s3",
|
|
OriginError: err,
|
|
}
|
|
}
|
|
return bunrouter.JSON(w, postImageOutput{
|
|
Id: image.Id,
|
|
Extension: image.Extension,
|
|
Uploader: image.Uploader,
|
|
UploadTS: image.UploadTS,
|
|
})
|
|
}
|