-
Notifications
You must be signed in to change notification settings - Fork 11
/
main.go
104 lines (86 loc) · 2.26 KB
/
main.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
package main
//go:generate esc -o generator/data/tpl/tpl.go -modtime 0 -pkg=tpl generator/template
//go:generate esc -o util/protoapi_include.go -modtime 0 -pkg=util proto
import (
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"runtime/debug"
"strconv"
"github.com/golang/protobuf/proto"
"github.com/yoozoo/protoapi/cmd"
"github.com/yoozoo/protoapi/generator"
"github.com/yoozoo/protoapi/util"
)
func main() {
defer func() {
util.CleanIncludePath()
if r := recover(); r != nil {
log.Printf("%s: %s", r, debug.Stack())
os.Exit(1)
}
}()
stat, err := os.Stdin.Stat()
args := os.Args
// when no any parameter and not reading from char device, treat it as being called by protoc
if len(args) == 1 && err == nil && (stat.Mode()&os.ModeCharDevice) == 0 {
// check for PROTOAPI_PORT, if set means it's in go test
protoapiPort := os.Getenv("PROTOAPI_PORT")
if protoapiPort != "" {
resp, err := http.Post("http://127.0.0.1:"+protoapiPort+"/", "application/protobuf", os.Stdin)
defer resp.Body.Close()
if err != nil {
util.Die(err)
}
body, err := ioutil.ReadAll(resp.Body)
os.Stdout.Write(body)
return
}
input, err := ioutil.ReadAll(os.Stdin)
if err != nil {
util.Die(fmt.Errorf("reading stdin error: %s", err.Error()))
}
response := generator.Generate(input)
output, err := proto.Marshal(response)
if err != nil {
util.Die(fmt.Errorf("create response failed: %s", err.Error()))
}
_, err = os.Stdout.Write(output)
if err != nil {
util.Die(err)
}
} else {
cmd.Execute()
}
}
func handler(w http.ResponseWriter, r *http.Request) {
input, err := ioutil.ReadAll(r.Body)
if err != nil {
w.Write([]byte(fmt.Errorf("reading error: %s", err.Error()).Error()))
return
}
response := generator.Generate(input)
output, err := proto.Marshal(response)
if err != nil {
w.Write([]byte(fmt.Errorf("reading error: %s", err.Error()).Error()))
return
}
_, err = w.Write(output)
if err != nil {
log.Println(err)
}
}
func serv() {
http.HandleFunc("/", handler)
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
panic(err)
}
port := listener.Addr().(*net.TCPAddr).Port
os.Setenv("PROTOAPI_PORT", strconv.Itoa(port))
defer os.Unsetenv("PROTOAPI_PORT")
log.Fatal(http.Serve(listener, nil))
}