Skip to content

Instantly share code, notes, and snippets.

@apparentlymart
Created May 15, 2016 19:48
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save apparentlymart/b4ef5854d0c5ca06d9674715259a95f0 to your computer and use it in GitHub Desktop.
Save apparentlymart/b4ef5854d0c5ca06d9674715259a95f0 to your computer and use it in GitHub Desktop.
Golang and Terminal.js web terminal
<html>
<head>
<script src="/terminal.js/dist/terminal.js"></script>
<style>
#terminal {
background: #000000;
color: #ffffff;
display: inline-block;
padding: 10px;
}
</style>
</head>
<body>
<pre id="terminal"></pre>
<script>
var elem = document.getElementById("terminal");
elem.tabindex = 0; // make the terminal focusable
var terminal = new Terminal();
var input = terminal.dom(elem);
var socket = new WebSocket('ws://'+document.location.host+'/echo', 'echo');
socket.addEventListener("open", function () {
input.on('data', function (evt) {
socket.send(evt);
});
});
socket.addEventListener("message", function (evt) {
terminal.write(event.data);
});
</script>
</body>
</html>
package main
import (
"fmt"
"io"
"net/http"
"os"
"os/exec"
"github.com/kr/pty"
"golang.org/x/net/websocket"
)
func ShellServer(ws *websocket.Conn) {
c := exec.Command("bash")
f, err := pty.Start(c)
if err != nil {
ws.Write([]byte(fmt.Sprintf("Error creating pty: %s\r\n", err)))
ws.Close()
return
}
go io.Copy(ws, f)
io.Copy(f, ws)
ws.Close()
}
func main() {
http.Handle("/", http.FileServer(http.Dir(os.Getenv("GOPATH")+"/src/github.com/apparentlymart/web-terminal-prototype")))
http.Handle("/echo", websocket.Handler(ShellServer))
err := http.ListenAndServe(":12345", nil)
if err != nil {
panic(err)
}
os.Exit(0)
}
@infamy
Copy link

infamy commented Apr 6, 2018

Which terminal.js library did you use?

@zerosuxx
Copy link

zerosuxx commented Sep 8, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment