Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update go generator base #4

Merged
merged 1 commit into from
Feb 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion generators.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
{
"name": "Ambassador Labs Go Generator",
"description": "Generates a new project for an API server writen in go",
"version": "0.0.1",
"version": "0.0.2",
"languages": ["go"],
"dir_name": "go"
}]
Expand Down
29 changes: 13 additions & 16 deletions generators/go/base/internal/binary/handlers.go.template
Original file line number Diff line number Diff line change
@@ -1,24 +1,10 @@
package api

import (
"log"
"net/http"
"time"
)

// Handles returning a 404 to the client and logging a message for unsupported routes
func handle404(w http.ResponseWriter, r *http.Request) {
log.Printf("request to %s, path not found, method: %s\n", r.URL, r.Method)
http.NotFound(w, r)
}

// Handles returning a simple about message
func handleAbout(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte(" {{{ .ProjectName }}}: server generated by Ambassador Labs"))
}


// responseWriter is a custom http.ResponseWriter that captures the status code.
type responseWriter struct {
http.ResponseWriter
Expand Down Expand Up @@ -49,8 +35,19 @@ func (rw *responseWriter) Write(b []byte) (int, error) {
return rw.ResponseWriter.Write(b)
}

// Handles returning a 404 to the client and logging a message for unsupported routes
func (s *apiService) handle404(w http.ResponseWriter, r *http.Request) {
http.NotFound(w, r)
}

// Handles returning a simple about message
func (s *apiService) handleAbout(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte(" Sample Service: server generated by Ambassador Labs"))
}

// logMiddleware logs the request method, URL path, duration, and status code.
func logMiddleware(next http.Handler) http.Handler {
func (s *apiService) logMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()

Expand All @@ -59,6 +56,6 @@ func logMiddleware(next http.Handler) http.Handler {
next.ServeHTTP(wrappedWriter, r)

// Log with the captured status code.
log.Printf("%s %s %d %s\n", r.Method, r.URL.Path, wrappedWriter.statusCode, time.Since(start))
s.logger.Info().Msgf("%s %s %d %s", r.Method, r.URL.Path, wrappedWriter.statusCode, time.Since(start))
})
}
38 changes: 25 additions & 13 deletions generators/go/base/internal/binary/server.go.template
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,45 @@ package api

import (
"context"
"log"
"net/http"
"os"
"time"

"github.com/gorilla/mux"
"github.com/gorilla/mux"
"github.com/rs/zerolog"
"golang.org/x/sync/errgroup"
ctrl "sigs.k8s.io/controller-runtime"
)


type apiService struct {
logger zerolog.Logger
addr string
// TODO: optional k8s health checks
}

func NewAPIService() *apiService {
output := zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339}
logger := zerolog.New(output).With().Timestamp().Logger()
return &apiService{
addr: ":8080",
addr: ":8080",
logger: logger,
}
}

func (s *apiService) WithLogger(logger zerolog.Logger) *apiService {
s.logger = logger
return s
}

func (s *apiService) WithAddr(addr string) *apiService {
s.addr = addr
return s
}

// Starts the main loop for the server which manages and spins up one or more sub servers that listen for requests
func (s *apiService) Start() {
log.Println("{{{ .ProjectName }}} server is starting up")
s.logger.Info().Msg("{{{ .ProjectName }}} server is starting up")
ctx := ctrl.SetupSignalHandler()
g, gCtx := errgroup.WithContext(ctx)

Expand All @@ -39,21 +51,21 @@ func (s *apiService) Start() {
// Block here until shutdown signal
err := g.Wait()
if err != nil {
log.Printf("error occured starting {{{ .ProjectName }}} server: %s\n", err.Error())
s.logger.Info().Msgf("error occured starting {{{ .ProjectName }}} server: %s", err.Error())
}
log.Println("{{{ .ProjectName }}} server shutting down...")
s.logger.Info().Msg("{{{ .ProjectName }}} server shutting down...")
}

// Starts the sub server for the api endpoints
func (s *apiService) Serve(ctx context.Context) error {
router := mux.NewRouter().StrictSlash(true)

router.HandleFunc("/", handle404)
router.HandleFunc("/about", handleAbout)
router.HandleFunc("/", s.handle404)
router.HandleFunc("/about", s.handleAbout)

{{{ codeGenGorillaMux "router" }}}

loggedMux := logMiddleware(router)
loggedMux := s.logMiddleware(router)

server := &http.Server{
Addr: s.addr,
Expand All @@ -62,19 +74,19 @@ func (s *apiService) Serve(ctx context.Context) error {

errChan := make(chan error)
go func() {
log.Printf("starting {{{ .ProjectName }}} server, address: %s\n", s.addr)
s.logger.Info().Msgf("starting {{{ .ProjectName }}} server, address: %s", s.addr)
errChan <- server.ListenAndServe()
}()

// wait for shut down or error to occur
select {
case <-ctx.Done():
log.Println("{{{ .ProjectName }}} server graceful shutdown started")
s.logger.Info().Msg("{{{ .ProjectName }}} server graceful shutdown started")
server.Shutdown(ctx)
log.Println("{{{ .ProjectName }}} server successfully shutdown")
s.logger.Info().Msg("{{{ .ProjectName }}} server successfully shutdown")
return nil
case err := <-errChan:
log.Printf("{{{ .ProjectName }}} server shutdown with error: %s\n", err.Error())
s.logger.Info().Msgf("{{{ .ProjectName }}} server shutdown with error: %s", err.Error())
return err
}
}
2 changes: 1 addition & 1 deletion generators/go/generator-config.yaml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
metadata:
name: "Ambassador Labs Go Generator"
description: "Generates a new project for an API server writen in go"
version: "0.0.1"
version: "0.0.2"
languages: ["go"]

# Defines the base directory within the template folder.
Expand Down
Loading