This repository has been archived by the owner on Nov 9, 2017. It is now read-only.
/
client.go
112 lines (100 loc) · 2.22 KB
/
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package main
import (
"bytes"
"encoding/pem"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"strings"
"github.com/flynn/strowger/client"
"github.com/flynn/strowger/types"
)
func main() {
certPath := flag.String("cert", "", "path to DER encoded certificate for SSL, - for stdin")
keyPath := flag.String("key", "", "path to DER encoded private key for SSL, - for stdin")
flag.Parse()
if len(flag.Args()) != 2 {
fmt.Fprintf(os.Stderr, "Usage: %s [flags] domain service-name\n", os.Args[0])
flag.PrintDefaults()
os.Exit(64)
}
domain, serviceName := flag.Arg(0), flag.Arg(1)
var stdin []byte
var err error
if *certPath == "-" || *keyPath == "-" {
stdin, err = ioutil.ReadAll(os.Stdin)
if err != nil {
log.Fatal("Failed to read from stdin: ", err)
}
}
tlsCert, err := readCert(*certPath, stdin)
if err != nil {
return
}
tlsKey, err := readKey(*keyPath, stdin)
if err != nil {
return
}
client, err := client.New()
if err != nil {
log.Fatal(err)
}
conf := &strowger.HTTPRoute{
Service: serviceName,
Domain: domain,
TLSCert: string(tlsCert),
TLSKey: string(tlsKey),
}
if err := client.CreateRoute(conf.ToRoute()); err != nil {
log.Fatal(err)
}
}
func readCert(path string, stdin []byte) ([]byte, error) {
if path == "-" {
var buffer bytes.Buffer
var derBlock *pem.Block
for {
derBlock, stdin = pem.Decode(stdin)
if derBlock == nil {
break
}
if derBlock.Type == "CERTIFICATE" {
buffer.Write(pem.EncodeToMemory(derBlock))
}
}
if buffer.Len() > 0 {
return buffer.Bytes(), nil
}
log.Fatal("No certificate PEM blocks found in stdin")
}
return readFile(path)
}
func readKey(path string, stdin []byte) ([]byte, error) {
if path == "-" {
var derBlock *pem.Block
for {
derBlock, stdin = pem.Decode(stdin)
if derBlock == nil {
break
}
if strings.Contains(derBlock.Type, "PRIVATE KEY") {
return pem.EncodeToMemory(derBlock), nil
}
}
log.Fatal("No private key PEM blocks found in stdin")
}
return readFile(path)
}
func readFile(path string) ([]byte, error) {
if path == "" {
return nil, nil
}
contents, err := ioutil.ReadFile(path)
if err != nil {
log.Printf("Failed to open %s: %s", path, err)
return nil, err
}
return contents, nil
}