Skip to content

Commit

Permalink
ちょっと工事
Browse files Browse the repository at this point in the history
  • Loading branch information
murasame29 committed Nov 11, 2024
1 parent 22bc6d0 commit b718ce4
Show file tree
Hide file tree
Showing 5 changed files with 56 additions and 44 deletions.
8 changes: 2 additions & 6 deletions cmd/app/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,19 +45,15 @@ func run() error {
return err
}

// handler をinvoke
var handler http.Handler
if err := container.Invoke(func(h http.Handler) {
handler = h
}); err != nil {
handler, err := container.Invoke[http.Handler]()
if err != nil {
return err
}

server.New(
handler,
server.WithHost(config.Config.Server.Host),
server.WithPort(config.Config.Server.Port),
server.WithShutdownTimeout(config.Config.Server.ShutdownTimeout),
).RunWithGracefulShutdown(context.Background())

return nil
Expand Down
11 changes: 9 additions & 2 deletions internal/container/dig.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@ func NewContainer() error {
}

// Invoke は、 *dig.ContainerのInvokeをwrapしてる関数
func Invoke(f any, opts ...dig.InvokeOption) error {
return container.Invoke(f, opts...)
func Invoke[T any](opts ...dig.InvokeOption) (T, error) {
var r T
if err := container.Invoke(func(t T) error {
r = t
return nil
}, opts...); err != nil {
return r, err
}
return r, nil
}
40 changes: 40 additions & 0 deletions internal/framework/contexts/context.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package contexts

import (
"context"

"github.com/labstack/echo/v4"
)

type ContextKey string

func (c ContextKey) String() string {
return string(c)
}

const (
RequestID ContextKey = "x-request-id"
)

var contextkeys = []ContextKey{
RequestID,
}

func GetRequestID(ctx context.Context) string {
v, ok := ctx.Value(RequestID.String()).(string)
if !ok {
return ""
}
return v
}

// ConvertContext はecho.Contextのkeyをcopyしてcontext.Contextに変換
func ConvertContext(c echo.Context) context.Context {
ctx := context.Background()
for _, key := range contextkeys {
v := c.Get(key.String())
ctx = context.WithValue(ctx, key, v)
}

return ctx
}
26 changes: 0 additions & 26 deletions internal/router/info.go

This file was deleted.

15 changes: 5 additions & 10 deletions internal/router/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,13 @@ import (
"github.com/labstack/echo/v4"
)

type router struct {
engine *echo.Echo
}

// NewEcho は、echo/v4 を利用した http.Handlerを返す関数です。
func NewEcho() http.Handler {
router := &router{
engine: echo.New(),
}
engine := echo.New()

router.health()
router.info()
engine.GET("/healthz", func(c echo.Context) error {
return c.String(200, "OK")
})

return router.engine
return engine
}

0 comments on commit b718ce4

Please sign in to comment.