chat: refactor code
Kim committed
Oct 21, 2025 at 18:47 UTC
286c824b0bb5c954cb00f3a878161c8a15384dd9
2 files changed
+15
-16
cmd/example_chat/main.go
+1
-16
@@ -4,11 +4,9 @@ import (
4
"context"
5
"fmt"
6
"net"
7
- "net/http"
7
"os"
8
"os/signal"
9
"syscall"
11
- "time"
10
11
"github.com/gosuda/relaydns/relaydns"
12
"github.com/rs/zerolog/log"
@@ -50,17 +48,7 @@ func runChat(cmd *cobra.Command, args []string) error {
48
return fmt.Errorf("listen chat: %w", err)
49
}
50
hub := newHub()
53
- mux := http.NewServeMux()
54
- mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { serveIndex(w, r, flagName) })
55
- mux.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) { handleWS(w, r, hub) })
56
- srv := &http.Server{Handler: mux, ReadHeaderTimeout: 5 * time.Second, IdleTimeout: 60 * time.Second}
57
- go func() {
58
- log.Info().Msgf("[chat] http listening on %s", ln.Addr().String())
59
- if err := srv.Serve(ln); err != nil && err != http.ErrServerClosed {
60
- log.Error().Err(err).Msg("chat http error")
61
- cancel()
62
- }
63
- }()
51
+ go serveChatHTTP(ctx, ln, flagName, hub, cancel)
52
53
// 2) advertise over RelayDNS (HTTP tunneled via server /peer route)
54
client, err := relaydns.NewClient(ctx, relaydns.ClientConfig{
@@ -83,8 +71,5 @@ func runChat(cmd *cobra.Command, args []string) error {
71
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
72
<-sig
73
log.Info().Msg("[chat] shutting down")
86
- shutCtx, cancelFn := context.WithTimeout(context.Background(), 2*time.Second)
87
- _ = srv.Shutdown(shutCtx)
88
- cancelFn()
74
return nil
75
}
cmd/example_chat/view.go
+14
@@ -3,12 +3,14 @@ package main
3
import (
4
"context"
5
"html/template"
6
+ "net"
7
"net/http"
8
"sync"
9
"time"
10
11
"github.com/coder/websocket"
12
"github.com/coder/websocket/wsjson"
13
+ "github.com/rs/zerolog/log"
14
)
15
16
// simple in-memory chat hub
@@ -95,6 +97,18 @@ func serveIndex(w http.ResponseWriter, r *http.Request, name string) {
97
_ = indexTmpl.Execute(w, struct{ Name string }{Name: name})
98
}
99
100
+// serveChatHTTP hosts the chat UI and websocket endpoint on the provided listener.
101
+func serveChatHTTP(ctx context.Context, ln net.Listener, name string, h *hub, cancel context.CancelFunc) {
102
+ mux := http.NewServeMux()
103
+ mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { serveIndex(w, r, name) })
104
+ mux.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) { handleWS(w, r, h) })
105
+ log.Info().Msgf("[chat] http listening on %s", ln.Addr().String())
106
+ if err := http.Serve(ln, mux); err != nil && err != http.ErrServerClosed {
107
+ log.Error().Err(err).Msg("chat http error")
108
+ cancel()
109
+ }
110
+}
111
+
112
var indexTmpl = template.Must(template.New("chat").Parse(`<!DOCTYPE html>
113
<html lang="en">
114
<head>