79 lines
1.7 KiB
Go
79 lines
1.7 KiB
Go
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
|
|
serverGRPCCert []byte
|
|
grpcEndpoint string
|
|
|
|
http.Server
|
|
}
|
|
|
|
type MetadataResponse struct {
|
|
GRPCEndpoint string `json:"grpc_endpoint"`
|
|
}
|
|
|
|
func NewHTTPSever(store store.FileStore, certBytes []byte, grpcEndpoint string) *HTTPServer {
|
|
srv := &HTTPServer{
|
|
store: store,
|
|
serverGRPCCert: certBytes,
|
|
grpcEndpoint: grpcEndpoint,
|
|
}
|
|
|
|
r := chi.NewRouter()
|
|
r.Get("/server.pem", srv.ServerCertHandler)
|
|
r.Get("/metadata", srv.MetadataHandler)
|
|
r.Get("/files/{id}", srv.FileHandler)
|
|
|
|
srv.Handler = r
|
|
return srv
|
|
}
|
|
|
|
func (s *HTTPServer) ServerCertHandler(w http.ResponseWriter, r *http.Request) {
|
|
w.Write(s.serverGRPCCert)
|
|
}
|
|
func (s *HTTPServer) MetadataHandler(w http.ResponseWriter, r *http.Request) {
|
|
md := &MetadataResponse{
|
|
GRPCEndpoint: s.grpcEndpoint,
|
|
}
|
|
encoder := json.NewEncoder(w)
|
|
encoder.Encode(md)
|
|
}
|
|
|
|
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.ErrNoSuchItem {
|
|
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)
|
|
}
|