github.com/pojntfx/hydrapp/hydrapp@v0.0.0-20240516002902-d08759d6ca9f/pkg/generators/frontend_react_panrpc.go.tpl (about)

     1  package frontend
     2  
     3  //go:generate npm install
     4  //go:generate npm run build
     5  
     6  import (
     7  	"context"
     8  	"embed"
     9  	"io/fs"
    10  	"net"
    11  	"net/http"
    12  	"net/url"
    13  	"strings"
    14  
    15  	"github.com/pojntfx/hydrapp/hydrapp/pkg/utils"
    16  )
    17  
    18  var (
    19  	//go:embed out
    20  	UI embed.FS
    21  )
    22  
    23  func StartServer(context context.Context, addr string, backendURL string, localhostize bool) (string, func() error, error) {
    24  	if strings.TrimSpace(addr) == "" {
    25  		addr = ":0"
    26  	}
    27  
    28  	listener, err := net.Listen("tcp", addr)
    29  	if err != nil {
    30  		return "", nil, err
    31  	}
    32  
    33  	root := fs.FS(UI)
    34  	dist, err := fs.Sub(root, "out")
    35  	if err != nil {
    36  		panic(err)
    37  	}
    38  
    39  	go func() {
    40  		if err := http.Serve(listener, http.FileServer(http.FS(dist))); err != nil {
    41  			if strings.HasSuffix(err.Error(), "use of closed network connection") {
    42  				return
    43  			}
    44  
    45  			panic(err)
    46  		}
    47  	}()
    48  
    49  	url, err := url.Parse("http://" + listener.Addr().String())
    50  	if err != nil {
    51  		return "", nil, err
    52  	}
    53  
    54  	values := url.Query()
    55  
    56  	values.Set("socketURL", backendURL)
    57  
    58  	url.RawQuery = values.Encode()
    59  
    60  	if localhostize {
    61  		return utils.Localhostize(url.String()), listener.Close, nil
    62  	}
    63  
    64  	return url.String(), listener.Close, nil
    65  }