Skip to content

Instantly share code, notes, and snippets.

View percybolmer's full-sized avatar

ProgrammingPercy percybolmer

View GitHub Profile
// setupEventHandlers configures and adds all handlers
func (m *Manager) setupEventHandlers() {
m.handlers[EventSendMessage] = SendMessageHandler
}
// checkOrigin will check origin and return true if its allowed
func checkOrigin(r *http.Request) bool {
// Grab the request origin
origin := r.Header.Get("Origin")
switch origin {
// Update this to HTTPS
case "https://localhost:8080":
return true
func main() {
// Create a root ctx and a CancelFunc which can be used to cancel retentionMap goroutine
rootCtx := context.Background()
ctx, cancel := context.WithCancel(rootCtx)
defer cancel()
setupAPI(ctx)
function connectWebsocket(otp) {
// Check if the browser supports WebSocket
if (window["WebSocket"]) {
console.log("supports websockets");
// Connect to websocket using OTP as a GET parameter
conn = new WebSocket("wss://" + document.location.host + "/ws?otp="+ otp);
...
@percybolmer
percybolmer / openssl-gencert.bash
Created September 25, 2022 12:14
OpenSSL to generate localhost cert
#!/bin/bash
echo "creating server.key"
openssl genrsa -out server.key 2048
openssl ecparam -genkey -name secp384r1 -out server.key
echo "creating server.crt"
openssl req -new -x509 -sha256 -key server.key -out server.crt -batch -days 3650
package main
import (
"context"
"fmt"
"log"
"net/http"
)
func main() {
// loginHandler is used to verify an user authentication and return a one time password
func (m *Manager) loginHandler(w http.ResponseWriter, r *http.Request) {
type userLoginRequest struct {
Username string `json:"username"`
Password string `json:"password"`
}
var req userLoginRequest
err := json.NewDecoder(r.Body).Decode(&req)
// Manager is used to hold references to all Clients Registered, and Broadcasting etc
type Manager struct {
clients ClientList
// Using a syncMutex here to be able to lcok state before editing clients
// Could also use Channels to block
sync.RWMutex
// handlers are functions that are used to handle Events
handlers map[string]EventHandler
// otps is a map of allowed OTP to accept connections from
package main
import (
"context"
"time"
"github.com/google/uuid"
)
type OTP struct {
/**
* login will send a login request to the server and then
* connect websocket
* */
function login() {
let formData = {
"username": document.getElementById("username").value,
"password": document.getElementById("password").value
}
// Send the request