MCPcopy Create free account
hub / github.com/coder/wush / cpH

Function cpH

cmd/wasm/main_js.go:537–633  ·  view source on GitHub ↗
(onIncomingFile js.Value, downloadFile js.Value)

Source from the content-addressed store, hash-verified

535}
536
537func cpH(onIncomingFile js.Value, downloadFile js.Value) http.HandlerFunc {
538 return func(w http.ResponseWriter, r *http.Request) {
539 if r.Method != "POST" {
540 w.WriteHeader(http.StatusOK)
541 w.Write([]byte("OK"))
542 return
543 }
544
545 fiName := strings.TrimPrefix(r.URL.Path, "/")
546
547 // TODO: impl
548 peer := map[string]any{
549 "id": js.ValueOf(0),
550 "name": js.ValueOf(""),
551 "ip": js.ValueOf(""),
552 "cancel": js.FuncOf(func(this js.Value, args []js.Value) any {
553 return nil
554 }),
555 }
556
557 allow := make(chan bool)
558 onIncomingFile.Invoke(peer, fiName, r.ContentLength).
559 Call("then", js.FuncOf(func(this js.Value, args []js.Value) any {
560 allow <- args[0].Bool()
561 return nil
562 })).
563 Call("catch", js.FuncOf(func(this js.Value, args []js.Value) any {
564 fmt.Println("onIncomingFile failed:", args[0].String())
565 allow <- false
566 return nil
567 }))
568 if !<-allow {
569 w.WriteHeader(http.StatusForbidden)
570 w.Write([]byte("File transfer was denied"))
571 r.Body.Close()
572 return
573 }
574
575 underlyingSource := map[string]interface{}{
576 // start method
577 "start": js.FuncOf(func(this js.Value, args []js.Value) interface{} {
578 // The first and only arg is the controller object
579 controller := args[0]
580
581 // Process the stream in yet another background goroutine,
582 // because we can't block on a goroutine invoked by JS in Wasm
583 // that is dealing with HTTP requests
584 go func() {
585 // Close the response body at the end of this method
586 defer r.Body.Close()
587
588 // Read the entire stream and pass it to JavaScript
589 for {
590 // Read up to 1MB at a time
591 buf := make([]byte, 1024*1024)
592 n, err := r.Body.Read(buf)
593 if err != nil && err != io.EOF {
594 // Tell the controller we have an error

Callers 1

newWushFunction · 0.85

Calls 3

ReadMethod · 0.80
WriteMethod · 0.45
CloseMethod · 0.45

Tested by

no test coverage detected