Skip to content

Using a custom main.go with generated truss services

Zaq? Wiedmann edited this page Sep 29, 2020 · 3 revisions

Here is a way to wrap an http handler with a custom main.go

  1. Create your own NAME-service/cmd/NAME-custom-server/main.go
  2. See Run() in NAME-service/svc/server/run.go, the contents can be copy and pasted into your new main.go. Don't forget to add flags.Parse to the top of your new main()
  3. You'll end up with something like:
package main

import (
	"context"
	"flag"
	"net/http"

	// This Service
	"github.com/metaverse/truss/_example/echo-service/svc"
	"github.com/metaverse/truss/_example/echo-service/svc/server"
	"github.com/metaverse/truss/_example/echo-service/svc/server/cli"
)

func main() {
	// Update addresses if they have been overwritten by flags
	flag.Parse()

	service := handlers.NewService()
	endpoints := NewEndpoints(service)

	// Mechanical domain.
	errc := make(chan error)

	// Interrupt handler.
	go handlers.InterruptHandler(errc)

	// Debug listener.
	go func() {
		log.Println("transport", "debug", "addr", cfg.DebugAddr)

		m := http.NewServeMux()
		m.Handle("/debug/pprof/", http.HandlerFunc(pprof.Index))
		m.Handle("/debug/pprof/cmdline", http.HandlerFunc(pprof.Cmdline))
		m.Handle("/debug/pprof/profile", http.HandlerFunc(pprof.Profile))
		m.Handle("/debug/pprof/symbol", http.HandlerFunc(pprof.Symbol))
		m.Handle("/debug/pprof/trace", http.HandlerFunc(pprof.Trace))

		errc <- http.ListenAndServe(cfg.DebugAddr, m)
	}()

	// HTTP transport.
	go func() {
		log.Println("transport", "HTTP", "addr", cfg.HTTPAddr)
		h := svc.MakeHTTPHandler(endpoints)
		errc <- http.ListenAndServe(cfg.HTTPAddr, h)
	}()

	// gRPC transport.
	go func() {
		log.Println("transport", "gRPC", "addr", cfg.GRPCAddr)
		ln, err := net.Listen("tcp", cfg.GRPCAddr)
		if err != nil {
			errc <- err
			return
		}

		srv := svc.MakeGRPCServer(endpoints)
		s := grpc.NewServer()
		pb.RegisterRecurlyServer(s, srv)

		errc <- s.Serve(ln)
	}()

	// Run!
	log.Println("exit", <-errc)

}