-
-
Save sangam14/b4b467880a0415a3f53dc98f9705c4f6 to your computer and use it in GitHub Desktop.
Golang and Terminal.js web terminal
This file contains 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 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