Repository: gorilla/websocket
Pull request #889 (2024-01-23 06:56:30)

feat: format message type
### summary

The `messageType` and `message` can be retrieved using the readMessage method, i want to convert mt int to string by  `FormatMessageType` ? 😁 

```go
var upgrader = websocket.Upgrader{} // use default options

func echo(w http.ResponseWriter, r *http.Request) {
	c, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Print("upgrade:", err)
		return
	}
	defer c.Close()
	for {
		mt, message, err := c.ReadMessage()
		if err != nil {
			log.Println("read:", err)
			break
		}

		log.Printf("recv: %s, type: %s", message, websocket.FormatMessageType(mt))  // 😁

		err = c.WriteMessage(mt, message)
		if err != nil {
			log.Println("write:", err)
			break
		}
	}
}
```

AlexVulaj: Nice addition @rfyiamcool , thanks! Looks good to me.
codecov[bot]: ## [Codecov](https://app.codecov.io/gh/gorilla/websocket/pull/889?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=gorilla) Report
All modified and coverable lines are covered by tests :white_check_mark:
> Comparison is base [(`d08ee1a`)](https://app.codecov.io/gh/gorilla/websocket/commit/d08ee1ad9b8a1bad1b388165f85f7794a604b8e1?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=gorilla) 71.26% compared to head [(`181effb`)](https://app.codecov.io/gh/gorilla/websocket/pull/889?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=gorilla) 71.30%.
> Report is 1 commits behind head on main.


<details><summary>Additional details and impacted files</summary>


```diff
@@            Coverage Diff             @@
##             main     #889      +/-   ##
==========================================
+ Coverage   71.26%   71.30%   +0.03%     
==========================================
  Files          11       11              
  Lines        1587     1589       +2     
==========================================
+ Hits         1131     1133       +2     
  Misses        349      349              
  Partials      107      107              
```



</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/gorilla/websocket/pull/889?src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=gorilla).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=gorilla).


Patch:
diff --git a/conn.go b/conn.go
index f857110..2ac19e9 100644
--- a/conn.go
+++ b/conn.go
@@ -1263,3 +1263,15 @@ func FormatCloseMessage(closeCode int, text string) []byte {
 	copy(buf[2:], text)
 	return buf
 }
+
+var messageTypes = map[int]string{
+	TextMessage:   "TextMessage",
+	BinaryMessage: "BinaryMessage",
+	CloseMessage:  "CloseMessage",
+	PingMessage:   "PingMessage",
+	PongMessage:   "PongMessage",
+}
+
+func FormatMessageType(mt int) string {
+	return messageTypes[mt]
+}
diff --git a/examples/echo/client.go b/examples/echo/client.go
index 7d870bd..d53b81c 100644
--- a/examples/echo/client.go
+++ b/examples/echo/client.go
@@ -41,12 +41,12 @@ func main() {
 	go func() {
 		defer close(done)
 		for {
-			_, message, err := c.ReadMessage()
+			mt, message, err := c.ReadMessage()
 			if err != nil {
 				log.Println("read:", err)
 				return
 			}
-			log.Printf("recv: %s", message)
+			log.Printf("recv: %s, type: %s", message, websocket.FormatMessageType(mt))
 		}
 	}()
 
diff --git a/examples/echo/server.go b/examples/echo/server.go
index f9a0b7b..9804e6b 100644
--- a/examples/echo/server.go
+++ b/examples/echo/server.go
@@ -33,7 +33,8 @@ func echo(w http.ResponseWriter, r *http.Request) {
 			log.Println("read:", err)
 			break
 		}
-		log.Printf("recv: %s", message)
+
+		log.Printf("recv: %s, type: %s", message, websocket.FormatMessageType(mt))
 		err = c.WriteMessage(mt, message)
 		if err != nil {
 			log.Println("write:", err)


Test patch:
diff --git a/conn_test.go b/conn_test.go
index a3dde2d..f0c29c3 100644
--- a/conn_test.go
+++ b/conn_test.go
@@ -797,3 +797,20 @@ func TestFailedConnectionReadPanic(t *testing.T) {
 	}
 	t.Fatal("should not get here")
 }
+
+func TestFormatMessageType(t *testing.T) {
+	str := FormatMessageType(TextMessage)
+	if str != messageTypes[TextMessage] {
+		t.Error("failed to format message type")
+	}
+
+	str = FormatMessageType(CloseMessage)
+	if str != messageTypes[CloseMessage] {
+		t.Error("failed to format message type")
+	}
+
+	str = FormatMessageType(123)
+	if str != messageTypes[123] {
+		t.Error("failed to format message type")
+	}
+}