70 lines
1.4 KiB
Go
70 lines
1.4 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"io/ioutil"
|
|
"net/http"
|
|
|
|
shell "github.com/ipfs/go-ipfs-api"
|
|
"tulpa.dev/within/wasmcloud/cmd/internal"
|
|
"within.website/ln"
|
|
"within.website/olin/namegen"
|
|
)
|
|
|
|
func createHandler(w http.ResponseWriter, r *http.Request, u *User) {
|
|
if !u.CanCreateHandlers {
|
|
http.Error(w, "you can't create handlers, contact support", http.StatusForbidden)
|
|
return
|
|
}
|
|
|
|
ctx := r.Context()
|
|
sh := shell.NewShell(*ipfsURL)
|
|
data, err := ioutil.ReadAll(r.Body)
|
|
if err != nil {
|
|
ln.Error(ctx, err)
|
|
http.Error(w, "invalid data", http.StatusBadRequest)
|
|
return
|
|
}
|
|
r.Body.Close()
|
|
|
|
var hdlr internal.Handler
|
|
err = json.Unmarshal(data, &hdlr)
|
|
if err != nil {
|
|
ln.Error(ctx, err)
|
|
http.Error(w, "not json", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
switch string(hdlr.ABI) {
|
|
case string(internal.CWA), string(internal.Dagger):
|
|
default:
|
|
ln.Log(ctx, ln.Info("unknown ABI"), ln.F{"abi": hdlr.ABI})
|
|
http.Error(w, "unknown ABI", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
cid, err := sh.Add(bytes.NewBuffer(hdlr.WASM))
|
|
if err != nil {
|
|
ln.Error(ctx, err)
|
|
http.Error(w, "can't upload wasm to storage", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
n := namegen.Next()
|
|
h := Handler{
|
|
Name: n,
|
|
User: *u,
|
|
UserID: u.ID,
|
|
Path: cid,
|
|
}
|
|
|
|
if err := db.Save(&h).Error; err != nil {
|
|
ln.Error(ctx, err)
|
|
http.Error(w, "can't save record", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
json.NewEncoder(w).Encode(h)
|
|
}
|