Skip to content

Instantly share code, notes, and snippets.

@RussellLuo
Last active June 10, 2021 13:10
Show Gist options
  • Save RussellLuo/5e706323e215bd8cb840cb7ae6aabae7 to your computer and use it in GitHub Desktop.
Save RussellLuo/5e706323e215bd8cb840cb7ae6aabae7 to your computer and use it in GitHub Desktop.
An example illustrates how to manage Gin-based HTTP applications in appx.
package main
import (
"context"
"fmt"
"net/http"
"github.com/RussellLuo/appx"
"github.com/gin-gonic/gin"
)
type Hi struct {
Router gin.IRouter
}
func (h *Hi) Init(ctx appx.Context) error {
greeter := ctx.MustLoad("greeter").(*Greeter)
r := greeter.Router.Group("/hi")
r.GET("/", func(ctx *gin.Context) {
fmt.Println("Got a request for /hi")
})
h.Router = r
return nil
}
type Bye struct {
Router gin.IRouter
}
func (b *Bye) Init(ctx appx.Context) error {
greeter := ctx.MustLoad("greeter").(*Greeter)
r := greeter.Router.Group("/bye")
r.GET("/", func(ctx *gin.Context) {
fmt.Println("Got a request for /bye")
})
b.Router = r
return nil
}
type Greeter struct {
Router gin.IRouter
server *http.Server
}
func (g *Greeter) Init(ctx appx.Context) error {
r := gin.Default()
g.server = &http.Server{
Addr: ":8080",
Handler: r,
}
g.Router = r
return nil
}
func (g *Greeter) Start(ctx context.Context) error {
fmt.Println("Starting HTTP server")
go g.server.ListenAndServe() // nolint:errcheck
return nil
}
func (g *Greeter) Stop(ctx context.Context) error {
fmt.Println("Stopping HTTP server")
return g.server.Shutdown(ctx)
}
func main() {
r := appx.NewRegistry()
// Typically located in `func init()` of package hi.
r.MustRegister(appx.New("hi", new(Hi)).Require("greeter"))
// Typically located in `func init()` of package bye.
r.MustRegister(appx.New("bye", new(Bye)).Require("greeter"))
// Typically located in `func init()` of package greeter.
r.MustRegister(appx.New("greeter", new(Greeter)))
// Typically located in `func main()` of package main.
r.SetOptions(&appx.Options{
ErrorHandler: func(err error) {
fmt.Printf("err: %v\n", err)
},
})
// Installs the applications.
if err := r.Install(context.Background()); err != nil {
fmt.Printf("err: %v\n", err)
return
}
defer r.Uninstall()
// Run the long-running applications.
sig, err := r.Run()
if err != nil {
fmt.Printf("err: %v\n", err)
return
}
fmt.Printf("terminated due to: %s\n", sig.String())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment