package net import ( "embed" "log" "net" "net/http" "strings" "github.com/gorilla/websocket" ) //go:embed terminal.html var terminalHTML embed.FS var upgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, CheckOrigin: func(r *http.Request) bool { origin := r.Header.Get("Origin") if origin == "" { return true } host := r.Host hostname, _, err := net.SplitHostPort(host) if err != nil { hostname = host } if strings.EqualFold(origin, "http://"+host) || strings.EqualFold(origin, "https://"+host) || strings.EqualFold(origin, "http://"+hostname) || strings.EqualFold(origin, "https://"+hostname) { return true } if hn, _, err := net.SplitHostPort(r.RemoteAddr); err == nil && (hn == "127.0.0.1" || hn == "::1") { return true } log.Printf("ws rejected origin: %s (host: %s)", origin, r.Host) return false }, } func newHTTPMux(s *Server) *http.ServeMux { mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { data, err := terminalHTML.ReadFile("terminal.html") if err != nil { http.Error(w, "not found", http.StatusNotFound) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Write(data) }) mux.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) { ws, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Printf("ws upgrade error: %v", err) return } sess := &Session{ Conn: newWSConn(ws), State: StateAccountName, } s.hub.Add(sess) go s.handleSession(sess, s.handler) }) return mux }