isle/go/cmd/entrypoint/daemon_util.go

54 lines
1.1 KiB
Go
Raw Normal View History

package main
import (
"context"
"errors"
"fmt"
"isle/daemon"
"isle/daemon/jsonrpc2"
"net"
"net/http"
"dev.mediocregopher.com/mediocre-go-lib.git/mctx"
"dev.mediocregopher.com/mediocre-go-lib.git/mlog"
)
const daemonHTTPRPCPath = "/rpc/v0.json"
func newHTTPServer(
ctx context.Context, logger *mlog.Logger, rpc *daemon.RPC,
) (
*http.Server, error,
) {
socketPath := daemon.HTTPSocketPath()
l, err := net.Listen("unix", socketPath)
if err != nil {
return nil, fmt.Errorf(
"failed to listen on socket %q: %w", socketPath, err,
)
}
ctx = mctx.Annotate(ctx, "httpAddr", l.Addr().String())
logger.Info(ctx, "HTTP server socket created")
rpcHandler := jsonrpc2.Chain(
jsonrpc2.NewMLogMiddleware(logger.WithNamespace("rpc")),
jsonrpc2.ExposeServerSideErrorsMiddleware,
)(
jsonrpc2.NewDispatchHandler(&rpc),
)
httpMux := http.NewServeMux()
httpMux.Handle(daemonHTTPRPCPath, jsonrpc2.NewHTTPHandler(rpcHandler))
srv := &http.Server{Handler: httpMux}
go func() {
if err := srv.Serve(l); !errors.Is(err, http.ErrServerClosed) {
logger.Fatal(ctx, "HTTP server unexpectedly shut down", err)
}
}()
return srv, nil
}