add goa examples
This commit is contained in:
82
go/goa_example/cmd/host/grpc.go
Normal file
82
go/goa_example/cmd/host/grpc.go
Normal file
@@ -0,0 +1,82 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
pet_storepb "goa_example/gen/grpc/pet_store/pb"
|
||||
petstoresvr "goa_example/gen/grpc/pet_store/server"
|
||||
petstore "goa_example/gen/pet_store"
|
||||
"log"
|
||||
"net"
|
||||
"net/url"
|
||||
"sync"
|
||||
|
||||
grpcmiddleware "github.com/grpc-ecosystem/go-grpc-middleware"
|
||||
grpcmdlwr "goa.design/goa/v3/grpc/middleware"
|
||||
"goa.design/goa/v3/middleware"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/reflection"
|
||||
)
|
||||
|
||||
// handleGRPCServer starts configures and starts a gRPC server on the given
|
||||
// URL. It shuts down the server if any error is received in the error channel.
|
||||
func handleGRPCServer(ctx context.Context, u *url.URL, petStoreEndpoints *petstore.Endpoints, wg *sync.WaitGroup, errc chan error, logger *log.Logger, debug bool) {
|
||||
|
||||
// Setup goa log adapter.
|
||||
var (
|
||||
adapter middleware.Logger
|
||||
)
|
||||
{
|
||||
adapter = middleware.NewLogger(logger)
|
||||
}
|
||||
|
||||
// Wrap the endpoints with the transport specific layers. The generated
|
||||
// server packages contains code generated from the design which maps
|
||||
// the service input and output data structures to gRPC requests and
|
||||
// responses.
|
||||
var (
|
||||
petStoreServer *petstoresvr.Server
|
||||
)
|
||||
{
|
||||
petStoreServer = petstoresvr.New(petStoreEndpoints, nil)
|
||||
}
|
||||
|
||||
// Initialize gRPC server with the middleware.
|
||||
srv := grpc.NewServer(
|
||||
grpcmiddleware.WithUnaryServerChain(
|
||||
grpcmdlwr.UnaryRequestID(),
|
||||
grpcmdlwr.UnaryServerLog(adapter),
|
||||
),
|
||||
)
|
||||
|
||||
// Register the servers.
|
||||
pet_storepb.RegisterPetStoreServer(srv, petStoreServer)
|
||||
|
||||
for svc, info := range srv.GetServiceInfo() {
|
||||
for _, m := range info.Methods {
|
||||
logger.Printf("serving gRPC method %s", svc+"/"+m.Name)
|
||||
}
|
||||
}
|
||||
|
||||
// Register the server reflection service on the server.
|
||||
// See https://grpc.github.io/grpc/core/md_doc_server-reflection.html.
|
||||
reflection.Register(srv)
|
||||
|
||||
(*wg).Add(1)
|
||||
go func() {
|
||||
defer (*wg).Done()
|
||||
|
||||
// Start gRPC server in a separate goroutine.
|
||||
go func() {
|
||||
lis, err := net.Listen("tcp", u.Host)
|
||||
if err != nil {
|
||||
errc <- err
|
||||
}
|
||||
logger.Printf("gRPC server listening on %q", u.Host)
|
||||
errc <- srv.Serve(lis)
|
||||
}()
|
||||
|
||||
<-ctx.Done()
|
||||
logger.Printf("shutting down gRPC server at %q", u.Host)
|
||||
srv.Stop()
|
||||
}()
|
||||
}
|
||||
112
go/goa_example/cmd/host/http.go
Normal file
112
go/goa_example/cmd/host/http.go
Normal file
@@ -0,0 +1,112 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
petstoresvr "goa_example/gen/http/pet_store/server"
|
||||
petstore "goa_example/gen/pet_store"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
goahttp "goa.design/goa/v3/http"
|
||||
httpmdlwr "goa.design/goa/v3/http/middleware"
|
||||
"goa.design/goa/v3/middleware"
|
||||
)
|
||||
|
||||
// handleHTTPServer starts configures and starts a HTTP server on the given
|
||||
// URL. It shuts down the server if any error is received in the error channel.
|
||||
func handleHTTPServer(ctx context.Context, u *url.URL, petStoreEndpoints *petstore.Endpoints, wg *sync.WaitGroup, errc chan error, logger *log.Logger, debug bool) {
|
||||
|
||||
// Setup goa log adapter.
|
||||
var (
|
||||
adapter middleware.Logger
|
||||
)
|
||||
{
|
||||
adapter = middleware.NewLogger(logger)
|
||||
}
|
||||
|
||||
// Provide the transport specific request decoder and response encoder.
|
||||
// The goa http package has built-in support for JSON, XML and gob.
|
||||
// Other encodings can be used by providing the corresponding functions,
|
||||
// see goa.design/implement/encoding.
|
||||
var (
|
||||
dec = goahttp.RequestDecoder
|
||||
enc = goahttp.ResponseEncoder
|
||||
)
|
||||
|
||||
// Build the service HTTP request multiplexer and configure it to serve
|
||||
// HTTP requests to the service endpoints.
|
||||
var mux goahttp.Muxer
|
||||
{
|
||||
mux = goahttp.NewMuxer()
|
||||
}
|
||||
|
||||
// Wrap the endpoints with the transport specific layers. The generated
|
||||
// server packages contains code generated from the design which maps
|
||||
// the service input and output data structures to HTTP requests and
|
||||
// responses.
|
||||
var (
|
||||
petStoreServer *petstoresvr.Server
|
||||
)
|
||||
{
|
||||
eh := errorHandler(logger)
|
||||
petStoreServer = petstoresvr.New(petStoreEndpoints, mux, dec, enc, eh, nil)
|
||||
if debug {
|
||||
servers := goahttp.Servers{
|
||||
petStoreServer,
|
||||
}
|
||||
servers.Use(httpmdlwr.Debug(mux, os.Stdout))
|
||||
}
|
||||
}
|
||||
// Configure the mux.
|
||||
petstoresvr.Mount(mux, petStoreServer)
|
||||
|
||||
// Wrap the multiplexer with additional middlewares. Middlewares mounted
|
||||
// here apply to all the service endpoints.
|
||||
var handler http.Handler = mux
|
||||
{
|
||||
handler = httpmdlwr.Log(adapter)(handler)
|
||||
handler = httpmdlwr.RequestID()(handler)
|
||||
}
|
||||
|
||||
// Start HTTP server using default configuration, change the code to
|
||||
// configure the server as required by your service.
|
||||
srv := &http.Server{Addr: u.Host, Handler: handler}
|
||||
for _, m := range petStoreServer.Mounts {
|
||||
logger.Printf("HTTP %q mounted on %s %s", m.Method, m.Verb, m.Pattern)
|
||||
}
|
||||
|
||||
(*wg).Add(1)
|
||||
go func() {
|
||||
defer (*wg).Done()
|
||||
|
||||
// Start HTTP server in a separate goroutine.
|
||||
go func() {
|
||||
logger.Printf("HTTP server listening on %q", u.Host)
|
||||
errc <- srv.ListenAndServe()
|
||||
}()
|
||||
|
||||
<-ctx.Done()
|
||||
logger.Printf("shutting down HTTP server at %q", u.Host)
|
||||
|
||||
// Shutdown gracefully with a 30s timeout.
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
_ = srv.Shutdown(ctx)
|
||||
}()
|
||||
}
|
||||
|
||||
// errorHandler returns a function that writes and logs the given error.
|
||||
// The function also writes and logs the error unique ID so that it's possible
|
||||
// to correlate.
|
||||
func errorHandler(logger *log.Logger) func(context.Context, http.ResponseWriter, error) {
|
||||
return func(ctx context.Context, w http.ResponseWriter, err error) {
|
||||
id := ctx.Value(middleware.RequestIDKey).(string)
|
||||
_, _ = w.Write([]byte("[" + id + "] encoding: " + err.Error()))
|
||||
logger.Printf("[%s] ERROR: %s", id, err.Error())
|
||||
}
|
||||
}
|
||||
191
go/goa_example/cmd/host/main.go
Normal file
191
go/goa_example/cmd/host/main.go
Normal file
@@ -0,0 +1,191 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
exampleservice "goa_example"
|
||||
petstore "goa_example/gen/pet_store"
|
||||
"log"
|
||||
"net"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/signal"
|
||||
"sync"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// Define command line flags, add any other flag required to configure the
|
||||
// service.
|
||||
var (
|
||||
hostF = flag.String("host", "localhost", "Server host (valid values: localhost, integration)")
|
||||
domainF = flag.String("domain", "", "Host domain name (overrides host domain specified in service design)")
|
||||
httpPortF = flag.String("http-port", "", "HTTP port (overrides host HTTP port specified in service design)")
|
||||
grpcPortF = flag.String("grpc-port", "", "gRPC port (overrides host gRPC port specified in service design)")
|
||||
secureF = flag.Bool("secure", false, "Use secure scheme (https or grpcs)")
|
||||
dbgF = flag.Bool("debug", false, "Log request and response bodies")
|
||||
)
|
||||
flag.Parse()
|
||||
|
||||
// Setup logger. Replace logger with your own log package of choice.
|
||||
var (
|
||||
logger *log.Logger
|
||||
)
|
||||
{
|
||||
logger = log.New(os.Stderr, "[exampleservice] ", log.Ltime)
|
||||
}
|
||||
|
||||
// Initialize the services.
|
||||
var (
|
||||
petStoreSvc petstore.Service
|
||||
)
|
||||
{
|
||||
petStoreSvc = exampleservice.NewPetStore(logger)
|
||||
}
|
||||
|
||||
// Wrap the services in endpoints that can be invoked from other services
|
||||
// potentially running in different processes.
|
||||
var (
|
||||
petStoreEndpoints *petstore.Endpoints
|
||||
)
|
||||
{
|
||||
petStoreEndpoints = petstore.NewEndpoints(petStoreSvc)
|
||||
}
|
||||
|
||||
// Create channel used by both the signal handler and server goroutines
|
||||
// to notify the main goroutine when to stop the server.
|
||||
errc := make(chan error)
|
||||
|
||||
// Setup interrupt handler. This optional step configures the process so
|
||||
// that SIGINT and SIGTERM signals cause the services to stop gracefully.
|
||||
go func() {
|
||||
c := make(chan os.Signal, 1)
|
||||
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
|
||||
errc <- fmt.Errorf("%s", <-c)
|
||||
}()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
// Start the servers and send errors (if any) to the error channel.
|
||||
switch *hostF {
|
||||
case "localhost":
|
||||
{
|
||||
addr := "http://localhost:8088"
|
||||
u, err := url.Parse(addr)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "invalid URL %#v: %s\n", addr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if *secureF {
|
||||
u.Scheme = "https"
|
||||
}
|
||||
if *domainF != "" {
|
||||
u.Host = *domainF
|
||||
}
|
||||
if *httpPortF != "" {
|
||||
h, _, err := net.SplitHostPort(u.Host)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "invalid URL %#v: %s\n", u.Host, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
u.Host = net.JoinHostPort(h, *httpPortF)
|
||||
} else if u.Port() == "" {
|
||||
u.Host = net.JoinHostPort(u.Host, "80")
|
||||
}
|
||||
handleHTTPServer(ctx, u, petStoreEndpoints, &wg, errc, logger, *dbgF)
|
||||
}
|
||||
|
||||
{
|
||||
addr := "grpc://localhost:8080"
|
||||
u, err := url.Parse(addr)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "invalid URL %#v: %s\n", addr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if *secureF {
|
||||
u.Scheme = "grpcs"
|
||||
}
|
||||
if *domainF != "" {
|
||||
u.Host = *domainF
|
||||
}
|
||||
if *grpcPortF != "" {
|
||||
h, _, err := net.SplitHostPort(u.Host)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "invalid URL %#v: %s\n", u.Host, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
u.Host = net.JoinHostPort(h, *grpcPortF)
|
||||
} else if u.Port() == "" {
|
||||
u.Host = net.JoinHostPort(u.Host, "8080")
|
||||
}
|
||||
handleGRPCServer(ctx, u, petStoreEndpoints, &wg, errc, logger, *dbgF)
|
||||
}
|
||||
|
||||
case "integration":
|
||||
{
|
||||
addr := "http://localhost:8088"
|
||||
u, err := url.Parse(addr)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "invalid URL %#v: %s\n", addr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if *secureF {
|
||||
u.Scheme = "https"
|
||||
}
|
||||
if *domainF != "" {
|
||||
u.Host = *domainF
|
||||
}
|
||||
if *httpPortF != "" {
|
||||
h, _, err := net.SplitHostPort(u.Host)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "invalid URL %#v: %s\n", u.Host, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
u.Host = net.JoinHostPort(h, *httpPortF)
|
||||
} else if u.Port() == "" {
|
||||
u.Host = net.JoinHostPort(u.Host, "80")
|
||||
}
|
||||
handleHTTPServer(ctx, u, petStoreEndpoints, &wg, errc, logger, *dbgF)
|
||||
}
|
||||
|
||||
{
|
||||
addr := "grpc://localhost:8080"
|
||||
u, err := url.Parse(addr)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "invalid URL %#v: %s\n", addr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if *secureF {
|
||||
u.Scheme = "grpcs"
|
||||
}
|
||||
if *domainF != "" {
|
||||
u.Host = *domainF
|
||||
}
|
||||
if *grpcPortF != "" {
|
||||
h, _, err := net.SplitHostPort(u.Host)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "invalid URL %#v: %s\n", u.Host, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
u.Host = net.JoinHostPort(h, *grpcPortF)
|
||||
} else if u.Port() == "" {
|
||||
u.Host = net.JoinHostPort(u.Host, "8080")
|
||||
}
|
||||
handleGRPCServer(ctx, u, petStoreEndpoints, &wg, errc, logger, *dbgF)
|
||||
}
|
||||
|
||||
default:
|
||||
fmt.Fprintf(os.Stderr, "invalid host argument: %q (valid hosts: localhost|integration)\n", *hostF)
|
||||
}
|
||||
|
||||
// Wait for signal.
|
||||
logger.Printf("exiting (%v)", <-errc)
|
||||
|
||||
// Send cancellation signal to the goroutines.
|
||||
cancel()
|
||||
|
||||
wg.Wait()
|
||||
logger.Println("exited")
|
||||
}
|
||||
Reference in New Issue
Block a user