Container: Add Gin web service provider

This commit is contained in:
Muyao CHEN 2024-09-28 22:48:33 +02:00
parent f866f18cfd
commit f0b688ff8c
5 changed files with 64 additions and 2 deletions

View File

@ -16,6 +16,7 @@ type ServiceProvider interface {
InstantiateLater() bool InstantiateLater() bool
// Params defines the parameters needed to instantiate a service. // Params defines the parameters needed to instantiate a service.
// NOTE: First one should always be the container.
Params(Container) []interface{} Params(Container) []interface{}
// Name is the name of the service provider // Name is the name of the service provider

12
main.go
View File

@ -10,11 +10,19 @@ import (
"syscall" "syscall"
"time" "time"
"github.com/gin-gonic/gin" "git.vinchent.xyz/vinchent/go-web/framework"
"git.vinchent.xyz/vinchent/go-web/providers/webserver"
) )
func main() { func main() {
core := gin.New() container := framework.NewGoWebContainer()
webServiceProvider := &webserver.WebSrvProvider{}
container.Bind(webServiceProvider)
goWebGin := container.JustGet(webserver.WebSrvName).(*webserver.GoWebGin)
core := goWebGin.Engine
registerRouter(core) registerRouter(core)
server := &http.Server{ server := &http.Server{
Addr: ":8080", Addr: ":8080",

View File

@ -0,0 +1,3 @@
package webserver
const WebSrvName = "srv:gin"

View File

@ -0,0 +1,25 @@
package webserver
import "git.vinchent.xyz/vinchent/go-web/framework"
type WebSrvProvider struct{}
func (p *WebSrvProvider) Name() string {
return WebSrvName
}
func (p *WebSrvProvider) Register(c framework.Container) framework.NewInstance {
return NewGoWebGin
}
func (p *WebSrvProvider) Init(c framework.Container) error {
return nil
}
func (p *WebSrvProvider) InstantiateLater() bool {
return false
}
func (p *WebSrvProvider) Params(c framework.Container) []interface{} {
return []interface{}{c}
}

View File

@ -0,0 +1,25 @@
package webserver
import (
"git.vinchent.xyz/vinchent/go-web/framework"
"github.com/gin-gonic/gin"
)
type GoWebGin struct {
container framework.Container
Engine *gin.Engine
}
func NewGoWebGin(params ...interface{}) (interface{}, error) {
paramsLen := len(params)
container := params[0].(framework.Container)
ginOpts := make([]gin.OptionFunc, paramsLen-1)
for _, param := range params[1:] {
ginOpts = append(ginOpts, param.(gin.OptionFunc))
}
return &GoWebGin{
container: container,
Engine: gin.New(ginOpts...),
}, nil
}