Initial commit

This commit is contained in:
2021-12-03 23:04:09 +01:00
commit 85fd8de5cb
21 changed files with 1681 additions and 0 deletions

39
server/grpc.go Normal file
View File

@@ -0,0 +1,39 @@
package server
import (
"context"
"fmt"
"gitea.benny.dog/torjus/ezshare/pb"
"gitea.benny.dog/torjus/ezshare/store"
)
type GRPCFileServiceServer struct {
Hostname string
store store.FileStore
pb.UnimplementedFileServiceServer
}
func NewGRPCFileServiceServer(store store.FileStore) *GRPCFileServiceServer {
return &GRPCFileServiceServer{Hostname: "localhost:8051", store: store}
}
func (s *GRPCFileServiceServer) UploadFile(ctx context.Context, req *pb.UploadFileRequest) (*pb.UploadFileResponse, error) {
var f pb.File
f.Data = req.GetData()
id, err := s.store.StoreFile(&f)
if err != nil {
return nil, err
}
return &pb.UploadFileResponse{Id: id, FileUrl: fmt.Sprintf("%s/files/%s", s.Hostname, id)}, nil
}
func (s *GRPCFileServiceServer) GetFile(ctx context.Context, req *pb.GetFileRequest) (*pb.GetFileResponse, error) {
f, err := s.store.GetFile(req.Id)
if err != nil {
return nil, err
}
return &pb.GetFileResponse{File: f}, nil
}

57
server/http.go Normal file
View File

@@ -0,0 +1,57 @@
package server
import (
"encoding/json"
"fmt"
"net/http"
"gitea.benny.dog/torjus/ezshare/store"
"github.com/go-chi/chi/v5"
)
type HTTPServer struct {
store store.FileStore
http.Server
}
func NewHTTPSever(store store.FileStore) *HTTPServer {
srv := &HTTPServer{
store: store,
}
r := chi.NewRouter()
r.Get("/files/{id}", srv.FileHandler)
srv.Handler = r
return srv
}
func (s *HTTPServer) FileHandler(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
f, err := s.store.GetFile(id)
if err != nil {
if err == store.ErrNoSuchFile {
WriteErrorResponse(w, http.StatusNotFound, "file not found")
return
}
WriteErrorResponse(w, http.StatusInternalServerError, fmt.Sprintf("error: %s", err))
return
}
w.Header().Add("Content-Type", http.DetectContentType(f.Data))
w.Write(f.Data)
}
func WriteErrorResponse(w http.ResponseWriter, status int, message string) {
errMessage := struct {
Error string `json:"error"`
}{
Error: message,
}
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(status)
encoder := json.NewEncoder(w)
encoder.Encode(&errMessage)
}