From 35bd6d65bb7e031ca4f5754c9020942408a94696 Mon Sep 17 00:00:00 2001 From: William Petit Date: Wed, 12 Feb 2020 22:07:36 +0100 Subject: [PATCH] Add BuildInfo service and template data extension --- service/build/info.go | 7 +++++++ service/build/service.go | 43 ++++++++++++++++++++++++++++++++++++++++ service/template/data.go | 18 +++++++++++++++++ 3 files changed, 68 insertions(+) create mode 100644 service/build/info.go create mode 100644 service/build/service.go diff --git a/service/build/info.go b/service/build/info.go new file mode 100644 index 0000000..e4aa7a6 --- /dev/null +++ b/service/build/info.go @@ -0,0 +1,7 @@ +package build + +type Info struct { + ProjectVersion string + GitRef string + BuildDate string +} diff --git a/service/build/service.go b/service/build/service.go new file mode 100644 index 0000000..e058815 --- /dev/null +++ b/service/build/service.go @@ -0,0 +1,43 @@ +package build + +import ( + "github.com/pkg/errors" + "gitlab.com/wpetit/goweb/service" +) + +const ( + ServiceName service.Name = "build" +) + +func ServiceProvider(projectVersion, gitRef, buildDate string) service.Provider { + info := &Info{projectVersion, gitRef, buildDate} + + return func(ctn *service.Container) (interface{}, error) { + return info, nil + } +} + +// From retrieves the build informations in the given service container +func From(container *service.Container) (*Info, error) { + service, err := container.Service(ServiceName) + if err != nil { + return nil, errors.Wrapf(err, "error while retrieving '%s' service", ServiceName) + } + + srv, ok := service.(*Info) + if !ok { + return nil, errors.Errorf("retrieved service is not a valid '%s' service", ServiceName) + } + + return srv, nil +} + +// Must retrieves the user repository in the given service container or panic otherwise +func Must(container *service.Container) *Info { + srv, err := From(container) + if err != nil { + panic(err) + } + + return srv +} diff --git a/service/template/data.go b/service/template/data.go index 45ae18b..0f85dd8 100644 --- a/service/template/data.go +++ b/service/template/data.go @@ -1,5 +1,12 @@ package template +import ( + "net/http" + + "gitlab.com/wpetit/goweb/service" + "gitlab.com/wpetit/goweb/service/build" +) + // Data is some data to inject into the template type Data map[string]interface{} @@ -17,3 +24,14 @@ func Extend(data Data, extensions ...DataExtFunc) (Data, error) { } return data, nil } + +func WithBuildInfo(w http.ResponseWriter, r *http.Request, ctn *service.Container) DataExtFunc { + return func(data Data) (Data, error) { + info, err := build.From(ctn) + if err != nil { + return nil, err + } + data["BuildInfo"] = info + return data, nil + } +}