Created
May 15, 2016 19:48
-
-
Save apparentlymart/b4ef5854d0c5ca06d9674715259a95f0 to your computer and use it in GitHub Desktop.
Golang and Terminal.js web terminal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Which terminal.js library did you use?