Package list golang-github-go-kit-kit / 344f645
add cmd flags, listen to signals, and use kit/log for logging Marcel Hauf 5 years ago
1 changed file(s) with 58 addition(s) and 13 deletion(s). Raw diff Collapse all Expand all
22 import (
33 "bytes"
44 "encoding/json"
5 "flag"
6 "fmt"
57 "io"
68 "io/ioutil"
7 "log"
9 stdlog "log"
810 "net/http"
911 "net/url"
12 "os"
13 "os/signal"
1014 "strings"
15 "syscall"
1116
1217 "golang.org/x/net/context"
1318
1621 "github.com/go-kit/kit/endpoint"
1722 "github.com/go-kit/kit/loadbalancer"
1823 "github.com/go-kit/kit/loadbalancer/consul"
19 klog "github.com/go-kit/kit/log"
24 log "github.com/go-kit/kit/log"
2025 httptransport "github.com/go-kit/kit/transport/http"
2126
2227 "github.com/hashicorp/consul/api"
2530 var (
2631 discoveryClient consul.Client
2732 ctx = context.Background()
33 logger log.Logger
2834 )
2935
3036 func main() {
37 fs := flag.NewFlagSet("", flag.ExitOnError)
38 var (
39 httpAddr = fs.String("http.addr", ":8000", "Address for HTTP (JSON) server")
40 consulAddr = fs.String("consul.addr", "", "Consul agent address")
41 )
42 flag.Usage = fs.Usage
43 if err := fs.Parse(os.Args[1:]); err != nil {
44 fmt.Fprintf(os.Stderr, "%v", err)
45 os.Exit(1)
46 }
3147
48 // log
49 logger = log.NewLogfmtLogger(os.Stderr)
50 logger = log.NewContext(logger).With("ts", log.DefaultTimestampUTC).With("caller", log.DefaultCaller)
51 stdlog.SetFlags(0) // flags are handled by Go kit's logger
52 stdlog.SetOutput(log.NewStdlibAdapter(logger)) // redirect anything using stdlib log to us
53
54 // errors
55 errc := make(chan error)
56 go func() {
57 errc <- interrupt()
58 }()
59
60 // consul
3261 consulConfig := api.DefaultConfig()
62 if len(*consulAddr) > 0 {
63 consulConfig.Address = *consulAddr
64 }
3365 consulClient, err := api.NewClient(consulConfig)
3466 if err != nil {
35 log.Fatal(err)
67 logger.Log("fatal", err)
3668 }
3769 discoveryClient = consul.NewClient(consulClient)
3870
39 r := mux.NewRouter()
40 r.HandleFunc("/api/{service}/{method}", apiGateway)
71 // apigateway
72 go func() {
73 r := mux.NewRouter()
74 r.HandleFunc("/api/{service}/{method}", apiGateway)
75 errc <- http.ListenAndServe(*httpAddr, r)
76 }()
4177
42 http.ListenAndServe(":8000", r)
78 // wait for interrupt/error
79 logger.Log("fatal", <-errc)
80 }
81
82 func interrupt() error {
83 c := make(chan os.Signal)
84 signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
85 return fmt.Errorf("%s", <-c)
4386 }
4487
4588 func apiGateway(w http.ResponseWriter, r *http.Request) {
4891 method := vars["method"]
4992 e, err := getEndpoint(service, method)
5093 if err != nil {
51 log.Print(err)
94 logger.Log("error", err)
5295 return
5396 }
5497
5699 dec := json.NewDecoder(r.Body)
57100 err = dec.Decode(&val)
58101 if err != nil {
59 log.Print(err)
102 logger.Log("warning", err)
103 fmt.Fprint(w, err)
60104 return
61105 }
62106
63107 resp, err := e(ctx, val)
64108 if err != nil {
65 log.Print(err)
109 logger.Log("warning", err)
110 fmt.Fprint(w, err)
66111 return
67112 }
68113 enc := json.NewEncoder(w)
69114 err = enc.Encode(resp)
70115 if err != nil {
71 log.Print(err)
116 logger.Log("warning", err)
117 fmt.Fprint(w, err)
72118 return
73119 }
74120 }
84130 }
85131 }
86132
87 publisher, err := consul.NewPublisher(discoveryClient, factory(ctx, method), klog.NewLogfmtLogger(&klog.StdlibWriter{}), se)
133 publisher, err := consul.NewPublisher(discoveryClient, factory(ctx, method), log.NewLogfmtLogger(&log.StdlibWriter{}), se)
134 publisher.Endpoints()
88135 if err != nil {
89136 return nil, err
90137 }
128175 }
129176
130177 func encodeRequest(r *http.Request, request interface{}) error {
131 log.Printf("encode req: %v", request)
132178 var buf bytes.Buffer
133179 if err := json.NewEncoder(&buf).Encode(request); err != nil {
134 log.Print(err)
135180 return err
136181 }
137182 r.Body = ioutil.NopCloser(&buf)