s3-share/internal/web/web.go

102 lines
2.2 KiB
Go
Raw Normal View History

2022-05-09 12:52:18 +00:00
package web
import (
"encoding/json"
"io"
"net/http"
"git.kapelle.org/niklas/s3share/internal/client"
"github.com/gorilla/mux"
"github.com/sirupsen/logrus"
)
type createShare struct {
Key string `json:"key"`
}
2022-05-09 13:36:43 +00:00
type deleteShare struct {
Slug string `json:"slug"`
}
2022-05-09 12:52:18 +00:00
func StartWebserver(addr string, client client.Client) error {
r := mux.NewRouter()
r.HandleFunc("/{slug:[a-zA-Z0-9]{6}}", func(w http.ResponseWriter, r *http.Request) {
})
r.HandleFunc("/s/{slug:[a-zA-Z0-9]{6}}", func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
share, err := client.GetShare(r.Context(), vars["slug"])
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if share == nil {
http.NotFound(w, r)
return
}
obj, err := client.GetObjectFromShare(r.Context(), share)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
_, err = io.Copy(w, obj)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
})
r.HandleFunc("/api/share", func(w http.ResponseWriter, r *http.Request) {
}).Methods("GET")
r.HandleFunc("/api/share", func(w http.ResponseWriter, r *http.Request) {
// TODO: check auth
var shareParams createShare
err := json.NewDecoder(r.Body).Decode(&shareParams)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
share, err := client.CreateShare(r.Context(), shareParams.Key)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(share)
}).Methods("POST")
r.HandleFunc("/api/share", func(w http.ResponseWriter, r *http.Request) {
2022-05-09 13:36:43 +00:00
//TODO: check auth
2022-05-09 12:52:18 +00:00
2022-05-09 13:36:43 +00:00
var shareParams deleteShare
err := json.NewDecoder(r.Body).Decode(&shareParams)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
err = client.DeleteShare(r.Context(), shareParams.Slug)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
2022-05-09 12:52:18 +00:00
}).Methods("DELETE")
logrus.Info("Starting webserver")
return http.ListenAndServe(addr, r)
}