diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..da86212 --- /dev/null +++ b/go.mod @@ -0,0 +1,5 @@ +module demo/websocket + +go 1.12 + +require github.com/gorilla/websocket v1.5.0 diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..e5a03d4 --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= +github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= diff --git a/hello.go b/hello.go new file mode 100644 index 0000000..56784ab --- /dev/null +++ b/hello.go @@ -0,0 +1,44 @@ +package main + +import ( + "fmt" + "net/http" + + "github.com/gorilla/websocket" +) + +func main() { + var upgrader = websocket.Upgrader{} + http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + http.ServeFile(w, r, "index.html") + }) + fs := http.FileServer(http.Dir("static/")) + http.Handle("/static/", http.StripPrefix("/static/", fs)) + http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) { + var conn, _ = upgrader.Upgrade(w, r, nil) + go func(conn *websocket.Conn) { + for { + mType, msg, err := conn.ReadMessage() + if err != nil { + println("close with error") + println(string(err.Error())) + conn.Close() + return + } + println((string(msg))) + switch mType { + case 1: + var sendmsg []byte = []byte("hi,I'm Go") + conn.WriteMessage(mType, sendmsg) + case 8: + fmt.Println("client close") + default: + fmt.Println("type::" + string(rune(mType))) + } + + } + }(conn) + }) + println("serve start") + http.ListenAndServe(":3000", nil) +} diff --git a/index.html b/index.html new file mode 100644 index 0000000..0b472e2 --- /dev/null +++ b/index.html @@ -0,0 +1,27 @@ + + + + + + +
Hello, World!
+ + + + \ No newline at end of file diff --git a/static/second.html b/static/second.html new file mode 100644 index 0000000..ddc5705 --- /dev/null +++ b/static/second.html @@ -0,0 +1 @@ +second page \ No newline at end of file