---
# System prepended metadata

title: 02. Websocket
tags: [golang練習]

---

# 02. Websocket
###### tags: `golang練習`

```go    
package main

import (
	"fmt"
	"html/template"
	"log"
	"net/http"

	"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

var err error

func main() {
	http.HandleFunc("/", page_render)
	http.HandleFunc("/ws", ws_connect)
	err := http.ListenAndServe(":3000", nil)
	if err != nil {
		log.Fatalf("ListenAndServ failed: ", err)
	}
}

func page_render(w http.ResponseWriter, r *http.Request) {
	t, err := template.ParseFiles("./render.html")
	if err != nil {
		log.Fatalf("template.ParseFiles failed: ", err)
	}
	t.Execute(w, nil)

}

func ws_connect(w http.ResponseWriter, r *http.Request) {
	//判斷請求是否為websocket升級請求。
	if websocket.IsWebSocketUpgrade(r) {
		conn, err := upgrader.Upgrade(w, r, w.Header())
		if err != nil {
			log.Fatalf("websocket upgrader.Upgrade failed: ", err)
		}
		conn.WriteMessage(websocket.TextMessage, []byte("The web socket is connected."))
		// 使用goroutine接收與回覆訊息
		go func() {
			for {
				t, c, err := conn.ReadMessage()
				if err != nil {
					// panic(err)
					// log.Fatalf("websocket conn.ReadMessage() failed: ", err)
					return
				}
				received := fmt.Sprintf("Message: \"%s\" received.", string(c))
				conn.WriteMessage(websocket.TextMessage, []byte(received))
				if t == -1 {
					return
				}
			}
		}()
	} else {
		fmt.Println("not connected")
	}
}

```
## main
1. **http.HandleFunc(url, handlerfunc)**
Define the url and what function you would like to use in it.
1. **http.ListenAndServe(port, handler)**
Run the server and keep it listening to this port.

## page_render(respond, request)
1. **template.ParesFiles(path):**
Load the file and create a template.
2. **(template).Execute(respond, data)**
Execute the template and set the data which contains variables which can be used like {{.}} in template.

## ws_connect(respond, request)
1. **websocket.IsWebSocketUpgrade(request)**
Check if the request asked to upgrade the connection to wescoket.
1. **websocket.upgrader**
Can set some configs in it and apply by .Upgrade
2. **(upgrader).Upgrade**
Upgrade the connection to webscoket and return the connection.
1. **(conn).WriteMessage(message_type, message []byte)**
Send message you would like to send.
1. **(conn).ReadMessage()**
Read message from the client.
