feat: profile picture fetching through guard service
This commit is contained in:
@ -4,6 +4,8 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@ -34,6 +36,7 @@ func NewUserHandler(repo *repository.Queries, minio *storage.FileStorage) *UserH
|
||||
func (h *UserHandler) RegisterRoutes(api chi.Router) {
|
||||
api.Post("/register", h.register)
|
||||
api.Put("/avatar", h.uploadAvatar)
|
||||
api.Get("/avatar/{avatar}", h.getAvatar)
|
||||
}
|
||||
|
||||
type RegisterParams struct {
|
||||
@ -93,6 +96,28 @@ func (h *UserHandler) register(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
func (h *UserHandler) getAvatar(w http.ResponseWriter, r *http.Request) {
|
||||
avatarObject := chi.URLParam(r, "avatar")
|
||||
|
||||
object, err := h.minio.GetObject(r.Context(), "guard-storage", avatarObject, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
web.Error(w, "avatar not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
defer object.Close()
|
||||
|
||||
stat, err := object.Stat()
|
||||
if err != nil {
|
||||
log.Printf("ERR: failed to get object stats: %v\n", err)
|
||||
web.Error(w, "failed to get avatar", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", stat.ContentType)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
io.Copy(w, object)
|
||||
}
|
||||
|
||||
func (h *UserHandler) uploadAvatar(w http.ResponseWriter, r *http.Request) {
|
||||
userId, ok := util.GetRequestUserId(r.Context())
|
||||
if !ok {
|
||||
@ -134,11 +159,9 @@ func (h *UserHandler) uploadAvatar(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
imageURL := fmt.Sprintf("http://%s/%s/%s", h.minio.EndpointURL().Host, "guard-storage", uploadInfo.Key)
|
||||
|
||||
if err := h.repo.UpdateProfilePicture(r.Context(), repository.UpdateProfilePictureParams{
|
||||
ProfilePicture: pgtype.Text{
|
||||
String: imageURL,
|
||||
String: uploadInfo.Key,
|
||||
Valid: true,
|
||||
},
|
||||
ID: user.ID,
|
||||
@ -148,14 +171,14 @@ func (h *UserHandler) uploadAvatar(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
type Response struct {
|
||||
URL string `json:"url"`
|
||||
AvatarID string `json:"url"`
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
encoder := json.NewEncoder(w)
|
||||
|
||||
if err := encoder.Encode(Response{URL: imageURL}); err != nil {
|
||||
if err := encoder.Encode(Response{AvatarID: uploadInfo.Key}); err != nil {
|
||||
web.Error(w, "failed to write response", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user