|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "net/http" |
| 7 | + "os" |
| 8 | + "os/signal" |
| 9 | + "syscall" |
| 10 | + "time" |
| 11 | + |
| 12 | + "github.com/hashicorp/consul/api" |
| 13 | + "github.com/hashicorp/consul/connect" |
| 14 | + "github.com/hashicorp/go-hclog" |
| 15 | + "github.com/nicholasjackson/env" |
| 16 | +) |
| 17 | + |
| 18 | +var name = env.String("SERVICE_NAME", false, "app", "Name of the service") |
| 19 | +var bindAddress = env.String("BIND_ADDRESS", false, "0.0.0.0", "Bind address of the service") |
| 20 | +var bindPort = env.Int("BIND_PORT", false, 9090, "Bind port of the service") |
| 21 | +var upstream = env.String("UPSTREAM", false, "", "Upstream service to call when the service receives an inbound request") |
| 22 | +var public = env.Bool("PUBLIC", false, false, "Does the service have a public API, if false the server is configured to use mTLS") |
| 23 | +var address = env.String("IP_ADDRESS", false, "localhost", "IP address of the service") |
| 24 | + |
| 25 | +func main() { |
| 26 | + log := hclog.Default() |
| 27 | + |
| 28 | + err := env.Parse() |
| 29 | + if err != nil { |
| 30 | + log.Error("Unable to parse environment", "error", err) |
| 31 | + os.Exit(1) |
| 32 | + } |
| 33 | + |
| 34 | + // // Create a Consul API client |
| 35 | + client, err := api.NewClient(api.DefaultConfig()) |
| 36 | + if err != nil { |
| 37 | + log.Error("Unable to create Consul client", "error", err) |
| 38 | + os.Exit(1) |
| 39 | + } |
| 40 | + |
| 41 | + // register the service |
| 42 | + serviceID := fmt.Sprintf("%s-%d", *name, time.Now().UnixNano()) |
| 43 | + client.Agent().ServiceRegister(&api.AgentServiceRegistration{ |
| 44 | + Name: *name, |
| 45 | + ID: serviceID, |
| 46 | + Address: *address, |
| 47 | + Port: *bindPort, |
| 48 | + Connect: &api.AgentServiceConnect{ |
| 49 | + Native: true, |
| 50 | + }, |
| 51 | + }) |
| 52 | + |
| 53 | + // Create an instance representing this service. "my-service" is the |
| 54 | + // name of _this_ service. The service should be cleaned up via Close. |
| 55 | + svc, err := connect.NewService(*name, client) |
| 56 | + if err != nil { |
| 57 | + log.Error("Unable to register service", "error", err) |
| 58 | + os.Exit(1) |
| 59 | + } |
| 60 | + defer svc.Close() |
| 61 | + |
| 62 | + // register the handler |
| 63 | + http.HandleFunc("/", handleRoot(svc, *upstream, log)) |
| 64 | + |
| 65 | + log.Info("Starting server", "address", *bindAddress, "port", *bindPort) |
| 66 | + if !*public { |
| 67 | + // The service is not public so create a HTTP server that serves via Connect |
| 68 | + server := &http.Server{ |
| 69 | + Addr: fmt.Sprintf("%s:%d", *bindAddress, *bindPort), |
| 70 | + TLSConfig: svc.ServerTLSConfig(), |
| 71 | + Handler: http.DefaultServeMux, |
| 72 | + // ... other standard fields |
| 73 | + } |
| 74 | + |
| 75 | + go server.ListenAndServeTLS("", "") |
| 76 | + } else { |
| 77 | + // Start a public server |
| 78 | + go http.ListenAndServe(fmt.Sprintf("%s:%d", *bindAddress, *bindPort), nil) |
| 79 | + } |
| 80 | + |
| 81 | + sigs := make(chan os.Signal, 1) |
| 82 | + done := make(chan bool, 1) |
| 83 | + |
| 84 | + signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) |
| 85 | + |
| 86 | + go func() { |
| 87 | + sig := <-sigs |
| 88 | + fmt.Println() |
| 89 | + fmt.Println(sig) |
| 90 | + done <- true |
| 91 | + }() |
| 92 | + |
| 93 | + fmt.Println("awaiting signal") |
| 94 | + <-done |
| 95 | + fmt.Println("exiting") |
| 96 | + |
| 97 | + client.Agent().ServiceDeregister(serviceID) |
| 98 | + |
| 99 | +} |
| 100 | + |
| 101 | +type Response struct { |
| 102 | + Service string `json:"service"` |
| 103 | + UpstreamCall *Response `json:"upstream_call,omitempty"` |
| 104 | +} |
| 105 | + |
| 106 | +func handleRoot(svc *connect.Service, upstream string, log hclog.Logger) func(rw http.ResponseWriter, r *http.Request) { |
| 107 | + return func(rw http.ResponseWriter, r *http.Request) { |
| 108 | + resp := Response{Service: svc.Name()} |
| 109 | + |
| 110 | + if upstream != "" { |
| 111 | + r, err := svc.HTTPClient().Get(upstream) |
| 112 | + if err != nil || r == nil || r.StatusCode != http.StatusOK { |
| 113 | + http.Error(rw, fmt.Sprintf("Unable to contact upstream, error: %s", err), http.StatusInternalServerError) |
| 114 | + return |
| 115 | + } |
| 116 | + |
| 117 | + upstreamResponse := &Response{} |
| 118 | + err = json.NewDecoder(r.Body).Decode(upstreamResponse) |
| 119 | + if err != nil { |
| 120 | + http.Error(rw, "Unable to decode upstream response", http.StatusInternalServerError) |
| 121 | + return |
| 122 | + } |
| 123 | + |
| 124 | + resp.UpstreamCall = upstreamResponse |
| 125 | + } |
| 126 | + |
| 127 | + err := json.NewEncoder(rw).Encode(resp) |
| 128 | + if err != nil { |
| 129 | + log.Error("Unable to write response", "error", err) |
| 130 | + } |
| 131 | + } |
| 132 | +} |
0 commit comments