forked from real-jacket/tutorials
-
Notifications
You must be signed in to change notification settings - Fork 0
/
web.go
89 lines (71 loc) · 1.77 KB
/
web.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package main
import (
"encoding/json"
"log"
"net/http"
"time"
"github.com/gorilla/websocket"
"github.com/micro/go-micro/v2"
"github.com/micro/go-micro/v2/transport/grpc"
"github.com/micro/go-micro/v2/web"
)
var upGrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true },
}
func main() {
// New web service
service := web.NewService(
web.Name("go.micro.api.websocket"),
web.MicroService(micro.NewService(micro.Transport(grpc.NewTransport()))),
)
service.Options().Service.Client()
if err := service.Init(); err != nil {
log.Fatal("Init", err)
}
// static files
service.Handle("/websocket/", http.StripPrefix("/websocket/", http.FileServer(http.Dir("html"))))
// websocket interface
service.HandleFunc("/websocket/hi", hi)
// websocket interface
service.HandleFunc("/websocket/hi2", hi2)
// websocket interface
service.HandleFunc("/websocket/hi3/hi3", hi2)
if err := service.Run(); err != nil {
log.Fatal("Run: ", err)
}
}
func hi2(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json; charset=utf-8")
_ = r.ParseForm()
// 返回结果
response := map[string]interface{}{
"ref": time.Now().UnixNano(),
"data": "Hello! " + r.Form.Get("name"),
}
// 返回JSON结构
if err := json.NewEncoder(w).Encode(response); err != nil {
http.Error(w, err.Error(), 500)
return
}
}
func hi(w http.ResponseWriter, r *http.Request) {
c, err := upGrader.Upgrade(w, r, nil)
if err != nil {
log.Printf("upgrade: %s", err)
return
}
defer c.Close()
for {
mt, message, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
break
}
log.Printf("recv: %s", message)
err = c.WriteMessage(mt, message)
if err != nil {
log.Println("write:", err)
break
}
}
}