gpaste/http.go

138 lines
3.4 KiB
Go
Raw Normal View History

2022-01-15 18:07:33 +00:00
package gpaste
2022-01-15 20:53:22 +00:00
import (
"encoding/json"
"io"
"net/http"
2022-01-16 20:29:42 +00:00
"strings"
2022-01-15 20:53:22 +00:00
"github.com/go-chi/chi/v5"
"github.com/google/uuid"
2022-01-15 21:32:24 +00:00
"go.uber.org/zap"
2022-01-15 20:53:22 +00:00
)
type HTTPServer struct {
2022-01-15 21:04:11 +00:00
store FileStore
config *ServerConfig
2022-01-15 21:32:24 +00:00
Logger *zap.SugaredLogger
2022-01-15 20:53:22 +00:00
http.Server
}
2022-01-15 21:04:11 +00:00
func NewHTTPServer(cfg *ServerConfig) *HTTPServer {
2022-01-15 20:53:22 +00:00
srv := &HTTPServer{
2022-01-15 21:04:11 +00:00
config: cfg,
2022-01-15 21:32:24 +00:00
Logger: zap.NewNop().Sugar(),
2022-01-15 20:53:22 +00:00
}
2022-01-15 21:04:11 +00:00
srv.store = NewMemoryFileStore()
2022-01-15 20:53:22 +00:00
r := chi.NewRouter()
r.Get("/", srv.HandlerIndex)
r.Post("/api/file", srv.HandlerAPIFilePost)
r.Get("/api/file/{id}", srv.HandlerAPIFileGet)
srv.Handler = r
return srv
}
func (s *HTTPServer) HandlerIndex(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("index"))
}
func (s *HTTPServer) HandlerAPIFilePost(w http.ResponseWriter, r *http.Request) {
f := &File{
ID: uuid.Must(uuid.NewRandom()).String(),
Body: r.Body,
}
2022-01-16 20:29:42 +00:00
// Check if multipart form
ct := r.Header.Get("Content-Type")
if strings.Contains(ct, "multipart/form-data") {
s.processMultiPartFormUpload(w, r)
return
}
2022-01-15 20:53:22 +00:00
err := s.store.Store(f)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
2022-01-15 21:32:24 +00:00
s.Logger.Warnw("Error storing file.", "erorr", err, "id", f.ID, "remote_addr", r.RemoteAddr)
2022-01-15 20:53:22 +00:00
return
}
2022-01-15 21:32:24 +00:00
s.Logger.Infow("Stored file.", "id", f.ID, "remote_addr", r.RemoteAddr)
2022-01-15 20:53:22 +00:00
var resp = struct {
Message string `json:"message"`
ID string `json:"id"`
URL string `json:"url"`
}{
Message: "OK",
ID: f.ID,
URL: "TODO",
}
w.WriteHeader(http.StatusAccepted)
encoder := json.NewEncoder(w)
if err := encoder.Encode(&resp); err != nil {
2022-01-15 21:32:24 +00:00
s.Logger.Warnw("Error encoding response to client.", "error", err, "remote_addr", r.RemoteAddr)
2022-01-15 20:53:22 +00:00
}
}
func (s *HTTPServer) HandlerAPIFileGet(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
if id == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
f, err := s.store.Get(id)
if err != nil {
// TODO: LOG
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
if _, err := io.Copy(w, f.Body); err != nil {
2022-01-15 21:32:24 +00:00
s.Logger.Warnw("Error writing file to client.", "error", err, "remote_addr", r.RemoteAddr)
2022-01-15 20:53:22 +00:00
}
}
2022-01-16 20:29:42 +00:00
func (s *HTTPServer) processMultiPartFormUpload(w http.ResponseWriter, r *http.Request) {
s.Logger.Debugw("Processing multipart form.")
type resp struct {
Message string `json:"message"`
ID string `json:"id"`
URL string `json:"url"`
}
var responses []resp
if err := r.ParseMultipartForm(1024 * 1024 * 10); err != nil {
2022-01-16 20:51:04 +00:00
s.Logger.Warnw("Error parsing multipart form.", "err", err)
2022-01-16 20:29:42 +00:00
}
for k := range r.MultipartForm.File {
ff, fh, err := r.FormFile(k)
if err != nil {
s.Logger.Warnw("Error reading file from multipart form.", "error", err)
return
}
f := &File{
ID: uuid.Must(uuid.NewRandom()).String(),
OriginalFilename: fh.Filename,
Body: ff,
}
if err := s.store.Store(f); err != nil {
w.WriteHeader(http.StatusInternalServerError)
s.Logger.Warnw("Error storing file.", "erorr", err, "id", f.ID, "remote_addr", r.RemoteAddr)
return
}
s.Logger.Infow("Stored file.", "id", f.ID, "filename", f.OriginalFilename, "remote_addr", r.RemoteAddr)
responses = append(responses, resp{Message: "OK", ID: f.ID, URL: "TODO"})
}
w.WriteHeader(http.StatusAccepted)
encoder := json.NewEncoder(w)
if err := encoder.Encode(&responses); err != nil {
s.Logger.Warnw("Error encoding response to client.", "error", err, "remote_addr", r.RemoteAddr)
}
}