Skip to content

Instantly share code, notes, and snippets.

View percybolmer's full-sized avatar

ProgrammingPercy percybolmer

View GitHub Profile
@percybolmer
percybolmer / gist:cb3872d5d040cf1bfd0c98f079b4ace0
Created July 17, 2023 06:50
Slog - Simplest JSON logging
package main
import (
"os"
"golang.org/x/exp/slog"
)
func main() {
jsonHandler := slog.NewJSONHandler(os.Stdout, nil)
--------App.svelte--------
<script>
 import Header from './Header.svelte';
</script>
<Header></Header>
<h1>Subtitle</h1>
<style>
package main
import (
"encoding/json"
"fmt"
"time"
)
// Event is the Messages sent over the websocket
// Used to differ between different actions
// Client is a websocket client, basically a frontend visitor
type Client struct {
// the websocket connection
connection *websocket.Conn
// manager is the manager used to manage the client
manager *Manager
// egress is used to avoid concurrent writes on the WebSocket
egress chan Event
// chatroom is used to know what room user is in
// setupEventHandlers configures and adds all handlers
func (m *Manager) setupEventHandlers() {
m.handlers[EventSendMessage] = SendMessageHandler
m.handlers[EventChangeRoom] = ChatRoomHandler
}
/**
* ChangeChatRoomEvent is used to switch chatroom
* */
class ChangeChatRoomEvent {
constructor(name) {
this.name = name;
}
}
/**
* changeChatRoom will update the value of selectedchat
/**
* routeEvent is a proxy function that routes
* events into their correct Handler
* based on the type field
* */
function routeEvent(event) {
if (event.type === undefined) {
alert("no 'type' field in event");
}
/**
* sendMessage will send a new message onto the Chat
* */
function sendMessage() {
var newmessage = document.getElementById("message");
if (newmessage != null) {
let outgoingEvent = new SendMessageEvent(newmessage.value, "percy");
sendEvent("send_message", outgoingEvent)
}
return false;
/**
* SendMessageEvent is used to send messages to other clients
* */
class SendMessageEvent {
constructor(message, from) {
this.message = message;
this.from = from;
}
}
/**
// NewMessageEvent is returned when responding to send_message
type NewMessageEvent struct {
SendMessageEvent
Sent time.Time `json:"sent"`
}
// SendMessageHandler will send out a message to all other participants in the chat
func SendMessageHandler(event Event, c *Client) error {
// Marshal Payload into wanted format
var chatevent SendMessageEvent