github.com/supabase/cli@v1.168.1/test/mocks/docker/httputils.go (about) 1 package docker 2 3 import ( 4 "fmt" 5 "io" 6 "net/http" 7 8 "github.com/docker/docker/pkg/ioutils" 9 "github.com/docker/docker/pkg/stdcopy" 10 "github.com/gin-gonic/gin" 11 ) 12 13 func CloseStreams(streams ...interface{}) { 14 for _, stream := range streams { 15 if tcpc, ok := stream.(interface { 16 CloseWrite() error 17 }); ok { 18 _ = tcpc.CloseWrite() 19 } else if closer, ok := stream.(io.Closer); ok { 20 _ = closer.Close() 21 } 22 } 23 } 24 25 func HijackedResponse(c *gin.Context, exitCode string, output ...string) { 26 // hijack the connection 27 hijacker, ok := c.Writer.(http.Hijacker) 28 if !ok { 29 c.JSON(http.StatusBadRequest, gin.H{ 30 "message": "error hijacking connection", 31 }) 32 return 33 } 34 conn, _, err := hijacker.Hijack() 35 if err != nil { 36 c.JSON(http.StatusBadRequest, gin.H{ 37 "message": "error hijacking connection", 38 }) 39 return 40 } 41 _, err = conn.Write([]byte{}) 42 if err != nil { 43 c.JSON(http.StatusBadRequest, gin.H{ 44 "message": "error hijacking connection", 45 }) 46 return 47 } 48 49 // write success code signalizing that the connection is established and ready to stream data 50 fmt.Fprintf(conn, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n") 51 52 // setup closer 53 closer := func() error { 54 CloseStreams(conn) 55 return nil 56 } 57 58 // write some output if command suppose to write to stdout 59 outStream := stdcopy.NewStdWriter(conn, stdcopy.Stdout) 60 if len(output) > 0 { 61 fmt.Fprint(outStream, output) 62 } 63 // finish with exit code and close stream and connection as the command is done 64 fmt.Fprintf(outStream, "exit code %s", exitCode) 65 rc := ioutils.NewReadCloserWrapper(conn, closer) 66 rc.Close() 67 }