go-socket.io 无效的传输方式

huangapple go评论173阅读模式
英文:

go-socket.io invalid transport

问题

我正在尝试使用go-socket.io库来构建一个使用golang的在线聊天应用程序,所以我按照文档中的示例创建了一个简单的结构。

我的main.go文件如下所示:

  1. package main
  2. import (
  3. "log"
  4. "net/http"
  5. "github.com/gin-gonic/gin"
  6. socketio "github.com/googollee/go-socket.io"
  7. )
  8. func GinMiddleware(allowOrigin string) gin.HandlerFunc {
  9. return func(c *gin.Context) {
  10. c.Writer.Header().Set("Access-Control-Allow-Origin", allowOrigin)
  11. c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
  12. c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")
  13. c.Writer.Header().Set("Access-Control-Allow-Headers", "Accept, Authorization, Content-Type, Content-Length, X-CSRF-Token, Token, session, Origin, Host, Connection, Accept-Encoding, Accept-Language, X-Requested-With")
  14. if c.Request.Method == http.MethodOptions {
  15. c.AbortWithStatus(http.StatusNoContent)
  16. return
  17. }
  18. c.Request.Header.Del("Origin")
  19. c.Next()
  20. }
  21. }
  22. func main() {
  23. router := gin.New()
  24. server := socketio.NewServer(nil)
  25. server.OnConnect("/", func(s socketio.Conn) error {
  26. s.SetContext("")
  27. log.Println("connected:", s.ID())
  28. return nil
  29. })
  30. server.OnEvent("/", "notice", func(s socketio.Conn, msg string) {
  31. log.Println("notice:", msg)
  32. s.Emit("reply", "have "+msg)
  33. })
  34. server.OnEvent("/chat", "msg", func(s socketio.Conn, msg string) string {
  35. s.SetContext(msg)
  36. return "recv " + msg
  37. })
  38. server.OnEvent("/", "bye", func(s socketio.Conn) string {
  39. last := s.Context().(string)
  40. s.Emit("bye", last)
  41. s.Close()
  42. return last
  43. })
  44. server.OnError("/", func(s socketio.Conn, e error) {
  45. log.Println("meet error:", e)
  46. })
  47. server.OnDisconnect("/", func(s socketio.Conn, msg string) {
  48. log.Println("closed", msg)
  49. })
  50. go func() {
  51. if err := server.Serve(); err != nil {
  52. log.Fatalf("socketio listen error: %s\n", err)
  53. }
  54. }()
  55. defer server.Close()
  56. router.Use(GinMiddleware("http://localhost:3000"))
  57. router.GET("/socket.io/*any", gin.WrapH(server))
  58. router.POST("/socket.io/*any", gin.WrapH(server))
  59. router.StaticFS("/public", http.Dir("../asset/index.html"))
  60. if err := router.Run(":8000"); err != nil {
  61. log.Fatal("failed run app: ", err)
  62. }
  63. }

我的前端代码如下所示:

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <title>Socket.IO chat</title>
  5. <style>
  6. * { margin: 0; padding: 0; box-sizing: border-box; }
  7. body { font: 13px Helvetica, Arial; }
  8. form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
  9. form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
  10. form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
  11. #messages { list-style-type: none; margin: 0; padding: 0; }
  12. #messages li { padding: 5px 10px; }
  13. #messages li:nth-child(odd) { background: #eee; }
  14. </style>
  15. </head>
  16. <body>
  17. <ul id="messages"></ul>
  18. <form action="">
  19. <input id="m" autocomplete="off" /><button>Send</button>
  20. </form>
  21. <script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
  22. <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
  23. <script>
  24. var socket = io();
  25. var s2 = io("/chat");
  26. socket.on('reply', function(msg){
  27. $('#messages').append($('<li>').text(msg));
  28. });
  29. $('form').submit(function(){
  30. s2.emit('msg', $('#m').val(), function(data){
  31. $('#messages').append($('<li>').text('ACK CALLBACK: ' + data));
  32. });
  33. socket.emit('notice', $('#m').val());
  34. $('#m').val('');
  35. return false;
  36. });
  37. </script>
  38. </body>
  39. </html>

但是当我在浏览器中运行代码,访问URL:http://localhost:8000/socket.io/ 时,我收到以下错误信息:

  1. invalid transport: %!s(<nil>)

为什么会出现这个错误?我尝试了一些来自以下网站的提示:

https://socket.io/docs/v3/troubleshooting-connection-issues/

但是没有任何方法对我有帮助。

英文:

I'm trying to use the go-socket.io library to build an online chat with golang
so I made a simple structure, following the examples in the documentation

my main.go looks like this:

  1. package main
  2. import (
  3. &quot;log&quot;
  4. &quot;net/http&quot;
  5. &quot;github.com/gin-gonic/gin&quot;
  6. socketio &quot;github.com/googollee/go-socket.io&quot;
  7. )
  8. func GinMiddleware(allowOrigin string) gin.HandlerFunc {
  9. return func(c *gin.Context) {
  10. c.Writer.Header().Set(&quot;Access-Control-Allow-Origin&quot;, allowOrigin)
  11. c.Writer.Header().Set(&quot;Access-Control-Allow-Credentials&quot;, &quot;true&quot;)
  12. c.Writer.Header().Set(&quot;Access-Control-Allow-Methods&quot;, &quot;POST, OPTIONS, GET, PUT, DELETE&quot;)
  13. c.Writer.Header().Set(&quot;Access-Control-Allow-Headers&quot;, &quot;Accept, Authorization, Content-Type, Content-Length, X-CSRF-Token, Token, session, Origin, Host, Connection, Accept-Encoding, Accept-Language, X-Requested-With&quot;)
  14. if c.Request.Method == http.MethodOptions {
  15. c.AbortWithStatus(http.StatusNoContent)
  16. return
  17. }
  18. c.Request.Header.Del(&quot;Origin&quot;)
  19. c.Next()
  20. }
  21. }
  22. func main() {
  23. router := gin.New()
  24. server := socketio.NewServer(nil)
  25. server.OnConnect(&quot;/&quot;, func(s socketio.Conn) error {
  26. s.SetContext(&quot;&quot;)
  27. log.Println(&quot;connected:&quot;, s.ID())
  28. return nil
  29. })
  30. server.OnEvent(&quot;/&quot;, &quot;notice&quot;, func(s socketio.Conn, msg string) {
  31. log.Println(&quot;notice:&quot;, msg)
  32. s.Emit(&quot;reply&quot;, &quot;have &quot;+msg)
  33. })
  34. server.OnEvent(&quot;/chat&quot;, &quot;msg&quot;, func(s socketio.Conn, msg string) string {
  35. s.SetContext(msg)
  36. return &quot;recv &quot; + msg
  37. })
  38. server.OnEvent(&quot;/&quot;, &quot;bye&quot;, func(s socketio.Conn) string {
  39. last := s.Context().(string)
  40. s.Emit(&quot;bye&quot;, last)
  41. s.Close()
  42. return last
  43. })
  44. server.OnError(&quot;/&quot;, func(s socketio.Conn, e error) {
  45. log.Println(&quot;meet error:&quot;, e)
  46. })
  47. server.OnDisconnect(&quot;/&quot;, func(s socketio.Conn, msg string) {
  48. log.Println(&quot;closed&quot;, msg)
  49. })
  50. go func() {
  51. if err := server.Serve(); err != nil {
  52. log.Fatalf(&quot;socketio listen error: %s\n&quot;, err)
  53. }
  54. }()
  55. defer server.Close()
  56. router.Use(GinMiddleware(&quot;http://localhost:3000&quot;))
  57. router.GET(&quot;/socket.io/*any&quot;, gin.WrapH(server))
  58. router.POST(&quot;/socket.io/*any&quot;, gin.WrapH(server))
  59. router.StaticFS(&quot;/public&quot;, http.Dir(&quot;../asset/index.html&quot;))
  60. if err := router.Run(&quot;:8000&quot;); err != nil {
  61. log.Fatal(&quot;failed run app: &quot;, err)
  62. }
  63. }

my front end looks like this:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

  1. &lt;!doctype html&gt;
  2. &lt;html&gt;
  3. &lt;head&gt;
  4. &lt;title&gt;Socket.IO chat&lt;/title&gt;
  5. &lt;style&gt;
  6. * { margin: 0; padding: 0; box-sizing: border-box; }
  7. body { font: 13px Helvetica, Arial; }
  8. form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
  9. form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
  10. form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
  11. #messages { list-style-type: none; margin: 0; padding: 0; }
  12. #messages li { padding: 5px 10px; }
  13. #messages li:nth-child(odd) { background: #eee; }
  14. &lt;/style&gt;
  15. &lt;/head&gt;
  16. &lt;body&gt;
  17. &lt;ul id=&quot;messages&quot;&gt;&lt;/ul&gt;
  18. &lt;form action=&quot;&quot;&gt;
  19. &lt;input id=&quot;m&quot; autocomplete=&quot;off&quot; /&gt;&lt;button&gt;Send&lt;/button&gt;
  20. &lt;/form&gt;
  21. &lt;script src=&quot;https://cdn.socket.io/socket.io-1.4.5.js&quot;&gt;&lt;/script&gt;
  22. &lt;script src=&quot;https://code.jquery.com/jquery-1.11.1.js&quot;&gt;&lt;/script&gt;
  23. &lt;script&gt;
  24. var socket = io();
  25. var s2 = io(&quot;/chat&quot;);
  26. socket.on(&#39;reply&#39;, function(msg){
  27. $(&#39;#messages&#39;).append($(&#39;&lt;li&gt;&#39;).text(msg));
  28. });
  29. $(&#39;form&#39;).submit(function(){
  30. s2.emit(&#39;msg&#39;, $(&#39;#m&#39;).val(), function(data){
  31. $(&#39;#messages&#39;).append($(&#39;&lt;li&gt;&#39;).text(&#39;ACK CALLBACK: &#39; + data));
  32. });
  33. socket.emit(&#39;notice&#39;, $(&#39;#m&#39;).val());
  34. $(&#39;#m&#39;).val(&#39;&#39;);
  35. return false;
  36. });
  37. &lt;/script&gt;
  38. &lt;/body&gt;
  39. &lt;/html&gt;

<!-- end snippet -->

but when running the code in the browser, by the url: http://localhost:8000/socket.io/
i get this error:

  1. invalid transport: %!s(&lt;nil&gt;)

why?
I tried to use some tips from this site:

  1. https://socket.io/docs/v3/troubleshooting-connection-issues/

but no alternative helped me

答案1

得分: 1

除了@code_monk指出的问题之外,下面的代码也是错误的:

  1. router.StaticFS("/public", http.Dir("../asset/index.html"))

正如其名称所示,http.Dir是一个目录而不是一个文件,所以正确的代码应该是:

  1. router.StaticFS("/public", http.Dir("../asset"))

在浏览器中打开的URL是:http://localhost:8080/public/。


如果你想提供单个文件,可以使用StaticFile

  1. router.StaticFile("/", "../asset/index.html")

在浏览器中打开的URL是:http://localhost:8080/。


还要注意../asset。也许你的意思是./asset(取决于你的文件目录结构)。

英文:

Besides the issue pointed out by @code_monk, the following code is incorrect too:

  1. router.StaticFS(&quot;/public&quot;, http.Dir(&quot;../asset/index.html&quot;))

As the name implies, http.Dir is a directory instead of a file, so the correct code should be:

  1. router.StaticFS(&quot;/public&quot;, http.Dir(&quot;../asset&quot;))

And the URL to open in the browser is: http://localhost:8080/public/.


If you want to serve a single file, you can use StaticFile instead:

  1. router.StaticFile(&quot;/&quot;, &quot;../asset/index.html&quot;)

And the URL to open in the browser is: http://localhost:8080/.


Pay attention to ../asset too. Maybe you mean ./asset (depends on the directory structure of your files).

huangapple
  • 本文由 发表于 2023年7月27日 21:51:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76780437.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定