Skip to content

Commit

Permalink
optimize master-gin
Browse files Browse the repository at this point in the history
  • Loading branch information
zhengshuxin committed Jan 11, 2022
1 parent feba1f6 commit 276be3a
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 18 deletions.
22 changes: 18 additions & 4 deletions examples/gin-server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"github.com/acl-dev/master-gin"
"github.com/acl-dev/master-go"
"github.com/gin-gonic/gin"
"net/http"
)

var (
Expand All @@ -23,6 +24,8 @@ var (

func main() {
fmt.Println("master-go version:", master.Version)
fmt.Println("mager-gin version:", master_gin.Version)

flag.Parse()

if !*debugMode {
Expand All @@ -36,16 +39,27 @@ func main() {
return
}

setupRoute(service.Engines)
setRoute(*service)
fmt.Println("Listen and running ...")
service.Run()
}

func setupRoute(engines []*gin.Engine) {
for _, e := range engines {
e.GET("/", func(context *gin.Context) {
func ginWrap(f func(w http.ResponseWriter, r *http.Request)) gin.HandlerFunc {
return func(context *gin.Context) {
f(context.Writer, context.Request)
}
}

func onTest(w http.ResponseWriter, _ *http.Request) {
_, _ = fmt.Fprintf(w, "test: Hello World!\r\n")
}

func setRoute(service master_gin.GinService) {
for _, s := range service.Servers {
s.Engine.GET("/", func(context *gin.Context) {
context.String(200, "hello world!\r\n")
})
s.Engine.GET("/test", ginWrap(onTest))
}
}

Expand Down
31 changes: 17 additions & 14 deletions gin_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,24 @@ import (

var (
g sync.WaitGroup // Used to wait for service to stop.
Version = "0.9.2"
)

type GinServ struct {
Listener net.Listener
Engine *gin.Engine
}

type GinService struct {
Alone bool
Listeners []net.Listener
Engines []*gin.Engine
Servers []*GinServ
}

// Run begin to start all the listening servers after Init() called.
func (service *GinService) Run() {
g.Add(len(service.Listeners))
for i := 0; i < len(service.Engines); i++ {
startServer(service.Listeners[i], service.Engines[i])
g.Add(len(service.Servers))
for _, s := range service.Servers {
startServer(s.Listener, s.Engine)
}

g.Wait()
Expand Down Expand Up @@ -55,15 +60,13 @@ func Init(addresses string, stopHandler func(bool)) (*GinService, error) {
return nil, err
}

var engines []*gin.Engine
for i := 0; i < len(listeners); i++ {
var service GinService

for _, l := range listeners {
engine := gin.Default()
engines = append(engines, engine)
serv := &GinServ{ Listener: l, Engine: engine }
service.Servers = append(service.Servers, serv)
}
service := &GinService{
Alone: master.Alone,
Listeners: listeners,
Engines: engines,
}
return service, nil

return &service, nil
}

0 comments on commit 276be3a

Please sign in to comment.