From c10ac23ece76516e0b7e73e6fac069699fdcb333 Mon Sep 17 00:00:00 2001 From: Adphi Date: Thu, 26 May 2022 12:14:54 +0200 Subject: [PATCH] add react single page app handler (proxy to dev server when $REACT_ENDPOINT is defined fix example Signed-off-by: Adphi --- example/example.go | 2 +- react/ui.go | 55 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) create mode 100644 react/ui.go diff --git a/example/example.go b/example/example.go index 353ae53..ce744ab 100644 --- a/example/example.go +++ b/example/example.go @@ -120,7 +120,7 @@ func run(opts ...service.Option) { panic(err) } RegisterGreeterServer(svc, &GreeterHandler{}) - metrics2.Register(svc) + metrics.Register(svc) go func() { if err := svc.Start(); err != nil { panic(err) diff --git a/react/ui.go b/react/ui.go new file mode 100644 index 0000000..eaaaf9d --- /dev/null +++ b/react/ui.go @@ -0,0 +1,55 @@ +// Copyright 2022 Linka Cloud All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package react + +import ( + "embed" + "io/fs" + "net/http" + "net/http/httputil" + "net/url" + "os" + "strings" +) + +func NewHandler(dir embed.FS, subpath string) (http.Handler, error) { + if e := os.Getenv("REACT_ENDPOINT"); e != "" { + return newProxy(e) + } + return newStatic(dir, subpath) +} + +func newStatic(dir embed.FS, subpath string) (http.Handler, error) { + s, err := fs.Sub(dir, subpath) + if err != nil { + return nil, err + } + fsrv := http.FileServer(http.FS(s)) + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if _, err := fs.Stat(s, strings.TrimPrefix(r.URL.Path, "/")); err != nil { + r.URL.Path = "/" + } + fsrv.ServeHTTP(w, r) + }), nil +} + +func newProxy(endpoint string) (http.Handler, error) { + u, err := url.Parse(endpoint) + if err != nil { + return nil, err + } + p := httputil.NewSingleHostReverseProxy(u) + return p, nil +}