Skip to content

Instantly share code, notes, and snippets.

@0xmovses
Created April 27, 2022 21:45
Show Gist options
  • Save 0xmovses/d62d81bbeffccb36708a9b0d92c93fd0 to your computer and use it in GitHub Desktop.
Save 0xmovses/d62d81bbeffccb36708a9b0d92c93fd0 to your computer and use it in GitHub Desktop.
simple go webhook
package main
import (
"fmt"
"log"
"net/http"
"os"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
func reader(conn *websocket.Conn) {
for {
messageType, p, err := conn.ReadMessage()
if err != nil {
log.Println(err)
return
}
log.Println(string(p))
if err := conn.WriteMessage(messageType, p); err != nil {
log.Println(err)
return
}
}
}
func homePage(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Home Page")
}
func wsEndpoint(w http.ResponseWriter, r *http.Request) {
//to allow cross origin requests
upgrader.CheckOrigin = func(r *http.Request) bool { return true }
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
}
log.Println("Client Connected")
reader(ws)
}
func setupRoutes() {
http.HandleFunc("/", homePage)
http.HandleFunc("/ws", wsEndpoint)
}
func main() {
fmt.Fprintf(os.Stdout, "Starting Server...\n")
setupRoutes()
fmt.Fprintf(os.Stdout, "Server Started\n")
log.Fatal(http.ListenAndServe(":8080", nil))
}
//---------------//
// for front-end test//
//-------------//
<html lang="en">
<head>
<meta charset="utf-8">
<title>________________</title>
<meta name="description" content="________________">
<meta name="author" content="________________">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="main.css">
</head>
<body>
<h1>Titolo</h1>
<p>Lorem ipsum...</p>
<script>
let socket = new WebSocket("ws://localhost:8080/ws")
console.log("Attempting websocket connectio")
socket.onopen = function(event) {
console.log("Connected to websocket")
socket.send("Hello from the client")
}
socket.onClose = (event) => {
console.log("Socket Closed Connection", event)
}
socket.onError = (error) => {
console.log("Socket Error", error)
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment