1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| package main
import ( "context" "embed" "github.com/gorilla/mux" _ "github.com/joho/godotenv/autoload" "log" "net/http" "os" "os/signal" "time" )
var ( view embed.FS )
func main() { quit := make(chan struct{}) r := mux.NewRouter() r.Handle("/", http.FileServer(http.FS(view))) r.HandleFunc("/", serveView).Methods(http.MethodGet) r.HandleFunc("/ws", serveWS).Methods(http.MethodGet) srv := http.Server{ Handler: r, Addr: ":80", WriteTimeout: 15 * time.Second, ReadTimeout: 15 * time.Second, } go func() { signals := make(chan os.Signal, 1) signal.Notify(signals, os.Interrupt) <-signals log.Println("Shutting down server...") if err := srv.Shutdown(context.Background()); err != nil { log.Println(err) } close(quit) }() if err := srv.ListenAndServe(); err != http.ErrServerClosed { log.Fatal(err) } <-quit }
func serveView(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "index.html") }
func serveWS(w http.ResponseWriter, r *http.Request) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Fatal(err) } client := &Client{ conn: conn, } go client.writePump() go client.readPump() }
|