witty/main.go

100 lines
1.7 KiB
Go
Raw Normal View History

2022-01-04 21:41:41 +01:00
package main
import (
"fmt"
"net/http"
"net/url"
2022-01-05 03:21:21 +01:00
"strings"
2022-01-04 21:41:41 +01:00
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
)
var host *string = nil
var upgrader = websocket.Upgrader{
2022-01-05 03:21:21 +01:00
ReadBufferSize: 4096,
2022-01-04 21:41:41 +01:00
WriteBufferSize: 4096,
CheckOrigin: func(r *http.Request) bool {
org := r.Header.Get("Origin")
2022-01-05 03:21:21 +01:00
h, err := url.Parse(org)
2022-01-04 21:41:41 +01:00
if err != nil {
return false
}
if (host == nil) || (*host != h.Host) {
fmt.Println("failed origin check of ", org, "against", *host)
}
return (host != nil) && (*host == h.Host)
},
}
// handle websockets
func wsHandler(w http.ResponseWriter, r *http.Request) {
2022-01-05 03:21:21 +01:00
conn, err := upgrader.Upgrade(w, r, nil)
2022-01-04 21:41:41 +01:00
2022-01-05 03:21:21 +01:00
if err != nil {
2022-01-04 21:41:41 +01:00
fmt.Println(err)
return
}
fmt.Println("Created the websocket")
for {
msgType, p, err := conn.ReadMessage()
2022-01-05 03:21:21 +01:00
if err != nil {
2022-01-04 21:41:41 +01:00
fmt.Println(err)
return
}
2022-01-05 03:21:21 +01:00
if err := conn.WriteMessage(msgType, p); err != nil {
2022-01-04 21:41:41 +01:00
fmt.Println(err)
return
}
}
}
// return files
2022-01-05 03:21:21 +01:00
func fileHandler(c *gin.Context, fname string) {
2022-01-04 21:41:41 +01:00
// if the URL has no fname, c.Param returns "/"
if fname == "/" {
fname = "/index.html"
host = &c.Request.Host
}
fname = fname[1:] //fname always starts with /
fmt.Println(fname)
if strings.HasSuffix(fname, "html") {
c.HTML(200, fname, nil)
} else {
//c.HTML interprets the file as HTML file
//we do not need that for regular files
c.File(fmt.Sprint("assets/", fname))
}
}
2022-01-05 03:21:21 +01:00
func main() {
2022-01-04 21:41:41 +01:00
rt := gin.Default()
rt.SetTrustedProxies(nil)
rt.LoadHTMLGlob("assets/*.html")
2022-01-05 03:21:21 +01:00
rt.GET("/*fname", func(c *gin.Context) {
2022-01-04 21:41:41 +01:00
fname := c.Param("fname")
// ws is a special case to create a new websocket
switch fname {
2022-01-05 03:21:21 +01:00
case "/ws":
2022-01-04 21:41:41 +01:00
wsHandler(c.Writer, c.Request)
default:
fileHandler(c, fname)
}
})
rt.Run(":8080")
2022-01-05 03:21:21 +01:00
}