-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
78 lines (66 loc) · 1.57 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
package main
import (
"context"
"flag"
"fmt"
"os"
"log"
"miaosha/pb"
"miaosha/service"
"net"
"net/http"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"google.golang.org/grpc"
_ "net/http/pprof"
run "runtime"
)
func main() {
run.SetBlockProfileRate(1)
go func() {
http.ListenAndServe(":8100", nil)
}()
if err := setLogPath(); err != nil {
log.Fatal("cannot set log file path: ", err)
}
port := flag.Int("port", 0, "the server port")
serverType := flag.String("type", "grpc", "the server type")
flag.Parse()
// register service
stockService := service.NewStockService()
grpcServer := grpc.NewServer()
pb.RegisterStockServer(grpcServer, stockService)
// listen connection
address := fmt.Sprintf("0.0.0.0:%d", *port)
listener, err := net.Listen("tcp", address)
if err != nil {
log.Fatal("can not start server: ", err)
}
if *serverType == "grpc" {
// grpc server
fmt.Printf("start grpc server:%s", address)
err = grpcServer.Serve(listener)
} else {
// rest server
fmt.Printf("start rest server:%s", address)
mux := runtime.NewServeMux()
err = pb.RegisterStockHandlerServer(context.Background(), mux, stockService)
if err != nil {
log.Fatal("register rest handle error: ", err)
}
err = http.Serve(listener, mux)
}
if err != nil {
log.Fatal("can not start server: ", err)
}
}
func setLogPath() error {
if err := os.MkdirAll("./log", 0777); err != nil {
return err
}
logFile, err := os.OpenFile("./log/stock.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
return err
}
log.SetOutput(logFile)
return nil
}