package bridge import ( "context" "errors" "fmt" "net/http" "strings" ) // NativeWriter is the response side of a native resource request // (implemented by window.ResourceWriter). type NativeWriter interface { Respond(status int, header http.Header) Write(p []byte) (int, error) Close(err error) } // ServeNative answers a request the WebView made to the app origin through // the native resource handler: "/" is the entry document, everything else // goes through the same router as bridge requests. Stream responses are // written through as they are produced. func (r *Router) ServeNative(ctx context.Context, origin, method, rawURL string, header http.Header, body []byte, w NativeWriter) { if !strings.HasPrefix(rawURL, origin+"/") { w.Respond(http.StatusForbidden, textHeader()) w.Write([]byte("not the app origin: " + rawURL)) return } local := rawURL[len(origin):] path, q, err := ParseLocalURL(local) if err != nil { w.Respond(http.StatusBadRequest, textHeader()) w.Write([]byte(err.Error())) return } if path == "/" { r.mu.RLock() entry := r.entry r.mu.RUnlock() path = "/assets/" + entry } req := &Request{Native: true, Method: strings.ToUpper(method), URL: local, Path: path, Query: q, Header: header, Body: body} resp, err := r.Serve(ctx, req) if err != nil { w.Close(err) return } h := resp.Header if h == nil { h = http.Header{} } h.Set("Cache-Control", "no-store") w.Respond(resp.Status, h) if resp.Stream != nil { if err := resp.Stream(ctx, w); err != nil && !errors.Is(err, context.Canceled) { w.Close(fmt.Errorf("%s %s: stream: %w", req.Method, req.Path, err)) return } w.Close(nil) return } if len(resp.Body) > 0 { w.Write(resp.Body) } w.Close(nil) } func textHeader() http.Header { h := http.Header{} h.Set("Content-Type", "text/plain; charset=utf-8") return h }