| 713 | } |
| 714 | |
| 715 | func (s *Handler) ServeHmrWS(w http.ResponseWriter, r *http.Request) { |
| 716 | if r.Header.Get("Upgrade") != "websocket" { |
| 717 | http.Error(w, "Bad Request", 400) |
| 718 | return |
| 719 | } |
| 720 | var upgrader = websocket.Upgrader{ |
| 721 | ReadBufferSize: 1024, |
| 722 | WriteBufferSize: 1024, |
| 723 | } |
| 724 | conn, err := upgrader.Upgrade(w, r, nil) |
| 725 | if err != nil { |
| 726 | http.Error(w, "Internal Server Error", 500) |
| 727 | return |
| 728 | } |
| 729 | defer conn.Close() |
| 730 | watchList := make(map[string]int64) |
| 731 | s.watchDataMapLock.Lock() |
| 732 | s.watchData[conn] = watchList |
| 733 | s.watchDataMapLock.Unlock() |
| 734 | defer func() { |
| 735 | s.watchDataMapLock.Lock() |
| 736 | delete(s.watchData, conn) |
| 737 | s.watchDataMapLock.Unlock() |
| 738 | }() |
| 739 | for { |
| 740 | messageType, data, err := conn.ReadMessage() |
| 741 | if err != nil { |
| 742 | break |
| 743 | } |
| 744 | if messageType == websocket.TextMessage { |
| 745 | msg := string(data) |
| 746 | if strings.HasPrefix(msg, "watch:") { |
| 747 | pathname := msg[6:] |
| 748 | if pathname != "" { |
| 749 | filename, _ := utils.SplitByFirstByte(pathname, '?') |
| 750 | fi, err := os.Lstat(filepath.Join(s.config.AppDir, filename)) |
| 751 | if err != nil { |
| 752 | if os.IsNotExist(err) { |
| 753 | // file not found, watch if it's created |
| 754 | watchList[pathname] = 0 |
| 755 | } else { |
| 756 | conn.WriteMessage(websocket.TextMessage, []byte("error:could not watch "+pathname)) |
| 757 | } |
| 758 | } else { |
| 759 | watchList[pathname] = fi.ModTime().UnixMilli() |
| 760 | } |
| 761 | } |
| 762 | } |
| 763 | } |
| 764 | } |
| 765 | } |
| 766 | |
| 767 | func (s *Handler) getAppImportMap() (importMapRaw []byte, importMap *importmap.ImportMap, err error) { |
| 768 | file, err := os.Open(filepath.Join(s.config.AppDir, "index.html")) |