-
Notifications
You must be signed in to change notification settings - Fork 29
/
api.go
84 lines (74 loc) · 1.96 KB
/
api.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
package eureka_client
import (
"errors"
"fmt"
"net/http"
"net/url"
"github.com/xuanbo/requests"
)
var (
// ErrNotFound 实例不存在,需要重新注册
ErrNotFound = errors.New("not found")
)
// 与eureka服务端rest交互
// https://github.com/Netflix/eureka/wiki/Eureka-REST-operations
// Register 注册实例
// POST /eureka/v2/apps/appID
func Register(zone, app string, instance *Instance) error {
// Instance 服务实例
type InstanceInfo struct {
Instance *Instance `json:"instance"`
}
var info = &InstanceInfo{
Instance: instance,
}
u := zone + "apps/" + app
// status: http.StatusNoContent
result := requests.Post(u).Json(info).Send().Status2xx()
return result.Err
}
// UnRegister 删除实例
// DELETE /eureka/v2/apps/appID/instanceID
func UnRegister(zone, app, instanceID string) error {
u := zone + "apps/" + app + "/" + instanceID
// status: http.StatusNoContent
result := requests.Delete(u).Send().StatusOk()
return result.Err
}
// Refresh 查询所有服务实例
// GET /eureka/v2/apps
func Refresh(zone string) (*Applications, error) {
type Result struct {
Applications *Applications `json:"applications"`
}
apps := new(Applications)
res := &Result{
Applications: apps,
}
u := zone + "apps"
err := requests.Get(u).Header("Accept", " application/json").Send().StatusOk().Json(res)
if err != nil {
return nil, err
}
return apps, nil
}
// Heartbeat 发送心跳
// PUT /eureka/v2/apps/appID/instanceID
func Heartbeat(zone, app, instanceID string) error {
u := zone + "apps/" + app + "/" + instanceID
params := url.Values{
"status": {"UP"},
}
result := requests.Put(u).Params(params).Send()
if result.Err != nil {
return result.Err
}
// 心跳 404 说明eureka server重启过,需要重新注册
if result.Resp.StatusCode == http.StatusNotFound {
return ErrNotFound
}
if result.Resp.StatusCode != http.StatusOK {
return fmt.Errorf("heartbeat failed, invalid status code: %d", result.Resp.StatusCode)
}
return nil
}