-
Notifications
You must be signed in to change notification settings - Fork 12
/
unix_client.go
95 lines (84 loc) · 2.12 KB
/
unix_client.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
90
91
92
93
94
95
package process_master
import (
"context"
"errors"
"fmt"
"io/ioutil"
"net"
"net/http"
"os/exec"
"time"
"github.com/eolinker/eosc/log"
"github.com/eolinker/eosc/service"
)
var (
ErrorProcessNotInit = errors.New("process not init")
)
type UnixClient struct {
addr string
name string
client *http.Client
timeout time.Duration
}
func (uc *UnixClient) DialContext(ctx context.Context, network, addr string) (net.Conn, error) {
if uc.addr == "" {
return nil, fmt.Errorf("%s %w", uc.name, ErrorProcessNotInit)
}
return net.DialTimeout("unix", uc.addr, uc.timeout)
}
func (uc *UnixClient) Update(process *exec.Cmd) {
log.DebugF("unix client update: %s %s", uc.name, process)
if process == nil {
uc.addr = ""
return
}
uc.addr = service.ServerUnixAddr(process.Process.Pid, uc.name)
}
func NewUnixClient(name string) *UnixClient {
ul := &UnixClient{
name: name,
}
transport := &http.Transport{
DialContext: ul.DialContext,
}
ul.client = &http.Client{Transport: transport}
return ul
}
func (uc *UnixClient) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
log.Debug("proxy:", request.RequestURI)
if uc.addr == "" {
writer.WriteHeader(http.StatusBadGateway)
fmt.Fprintf(writer, "%s %s", uc.name, ErrorProcessNotInit.Error())
return
}
req, err := http.NewRequest(request.Method, request.RequestURI, request.Body)
if err != nil {
writer.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(writer, "%v", err)
log.Warnf("clone request to unix error:%v", err)
return
}
req.URL.Scheme = "http"
req.URL.Host = uc.addr
req.Header = request.Header
resp, err := uc.client.Do(req)
if err != nil {
writer.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(writer, "%v", err)
log.Errorf("proxy to unix err:%v", err)
return
}
data, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
writer.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(writer, "%v", err)
log.Errorf("fetch error: reading %v", err)
return
}
for k, _ := range resp.Header {
writer.Header().Set(k, resp.Header.Get(k))
}
writer.WriteHeader(resp.StatusCode)
writer.Write(data)
}