Skip to content

Commit

Permalink
add builtin httpserver component
Browse files Browse the repository at this point in the history
  • Loading branch information
mkideal committed Aug 9, 2024
1 parent 01d2d98 commit a4781e2
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions component/builtin/httpserver.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package builtin

import (
"context"
"net/http"

"github.com/gopherd/core/component"
)

// HTTPServerComponent is the interface that wraps the Handle method.
type HTTPServerComponent interface {
Handle(path string, handler http.Handler)
}

const HTTPServerComponentName = "github.com/gopherd/core/component/httpserver"

func init() {
// Register the HTTPServerComponent implementation.
component.Register(HTTPServerComponentName, func() component.Component {
return new(httpServerComponent)
})
}

// Ensure httpServerComponent implements HTTPServerComponent interface.
var _ HTTPServerComponent = (*httpServerComponent)(nil)

type httpServerComponent struct {
component.BaseComponent[struct {
Addr string
DefaultServeMux bool
}]
mux *http.ServeMux
server *http.Server
}

func (com *httpServerComponent) Start(ctx context.Context) error {
if com.Options().DefaultServeMux {
com.mux = http.DefaultServeMux
} else {
com.mux = http.NewServeMux()
}
com.server = &http.Server{Addr: com.Options().Addr, Handler: com.mux}
go com.server.ListenAndServe()
return nil
}

func (com *httpServerComponent) Shutdown(ctx context.Context) error {
return com.server.Shutdown(ctx)
}

// Handle implements the HTTPServerComponent interface.
func (com *httpServerComponent) Handle(path string, handler http.Handler) {
com.mux.Handle(path, handler)
}

0 comments on commit a4781e2

Please sign in to comment.