登录
首页 >  Golang >  Go问答

在Golang路由中如何集成JavaScript的热加载功能来进行开发?

来源:stackoverflow

时间:2024-03-10 11:27:24 486浏览 收藏

小伙伴们对Golang编程感兴趣吗?是否正在学习相关知识点?如果是,那么本文《在Golang路由中如何集成JavaScript的热加载功能来进行开发?》,就很适合你,本篇文章讲解的知识点主要包括。在之后的文章中也会多多分享相关知识点,希望对大家的知识积累有所帮助!

问题内容

我想为 golang + svelte 设置下一个简单的开发设置

前端部分

$ npx degit sveltejs/template frontend
$ yarn
$ yarn dev # it start the frontend env on http://localhost:5000

所以我在 http://localhost:5000 上有一个正在运行的前端

后端部分

  • 在 :443 上使用 https 访问 net/http 路由器,并使用 mkcert 创建自签名证书
  • https://localhost/hello -> go handlers 用于显示正常的 go handlers
  • https://localhost/ -> 反向代理 http://localhost:5000
package main

import (
   "bytes"
   "io/ioutil"
   "log"
   "net/http"
   "net/http/httputil"
   "net/url"
   "strconv"
)

func newDirector(origin url.URL) func(*http.Request) {
   return func(req *http.Request) {
       req.Header.Add("X-Forwarded-Host", req.Host)
       req.Header.Add("X-Origin-Host", origin.Host)
       req.URL.Scheme = "http"
       req.URL.Host = origin.Host
   }
}

func newReplacer(orig, replace string) func(resp *http.Response) error {
   return func(resp *http.Response) error {
       b, err := ioutil.ReadAll(resp.Body)
       if err != nil {
           return err
       }

       err = resp.Body.Close()
       if err != nil {
           return err
       }

       b = bytes.Replace(b, []byte(orig), []byte(replace), -1)
       body := ioutil.NopCloser(bytes.NewReader(b))

       resp.Body = body
       resp.ContentLength = int64(len(b))
       resp.Header.Set("Content-Length", strconv.Itoa(len(b)))

       return nil
   }
}

func Frontend(w http.ResponseWriter, r *http.Request) {
   origin, _ := url.Parse("http://localhost:5000/")
   director := newDirector(*origin)
   proxy := &httputil.ReverseProxy{Director: director}
   proxy.ServeHTTP(w, r)
}

func liverload_js(w http.ResponseWriter, r *http.Request) {
   origin, _ := url.Parse("http://localhost:35729/")
   director := newDirector(*origin)
   modifier := newReplacer("this.port = 35729;", "this.port = 443;")
   proxy := &httputil.ReverseProxy{Director: director, ModifyResponse: modifier}
   proxy.ServeHTTP(w, r)
}

func liverload_ws(w http.ResponseWriter, r *http.Request) {
   origin, _ := url.Parse("http://localhost:35729/")
   director := newDirector(*origin)
   proxy := &httputil.ReverseProxy{Director: director}
   proxy.ServeHTTP(w, r)
}

func Bundle_js(w http.ResponseWriter, r *http.Request) {
   origin, _ := url.Parse("http://localhost:5000/")
   director := newDirector(*origin)
   modifier := newReplacer(":35729/livereload.js?snipver=1", ":443/livereload.js?snipver=1")
   proxy := &httputil.ReverseProxy{Director: director, ModifyResponse: modifier}
   proxy.ServeHTTP(w, r)
}

func main() {
   http.HandleFunc("/build/bundle.js", Bundle_js)
   http.HandleFunc("/livereload.js", liverload_js)
   http.HandleFunc("/livereload", liverload_ws)
   http.HandleFunc("/", Frontend)
   log.Fatal(http.ListenAndServeTLS(":443", "cert.pem", "key.pem", nil))
}

按 f5 进行重新加载,但热重新加载不会通过 ws 代理。

如何将其包含到代理中?


解决方案


自由职业者帮助我找到了答案。 诀窍是我在每个代理请求中使用了scheme=“http”,甚至httputil.reverseproxy本身就支持websocket。

func newdirector(origin url.url) func(*http.request) {
   return func(req *http.request) {
       req.header.add("x-forwarded-host", req.host)
       req.header.add("x-origin-host", origin.host)
       req.url.scheme = "http"
       req.url.host = origin.host
   }
}

应该是

func newdirector(origin url.url) func(*http.request) {
   return func(req *http.request) {
       req.header.add("x-forwarded-host", req.host)
       req.header.add("x-origin-host", origin.host)
       req.url.scheme = origin.scheme
       req.url.host = origin.host
   }
}

完整的代码变成了

package main

import (
    "bytes"
    "io/ioutil"
    "log"
    "net/http"
    "net/http/httputil"
    "net/url"
    "strconv"
)

func newdirector(origin url.url) func(*http.request) {
    return func(req *http.request) {
        req.header.add("x-forwarded-host", req.host)
        req.header.add("x-origin-host", origin.host)
        req.url.scheme = origin.scheme
        req.url.host = origin.host
    }
}

func newreplacer(orig, replace string) func(resp *http.response) error {
    return func(resp *http.response) error {
        b, err := ioutil.readall(resp.body)
        if err != nil {
            return err
        }

        err = resp.body.close()
        if err != nil {
            return err
        }

        b = bytes.replace(b, []byte(orig), []byte(replace), -1)
        body := ioutil.nopcloser(bytes.newreader(b))

        resp.body = body
        resp.contentlength = int64(len(b))
        resp.header.set("content-length", strconv.itoa(len(b)))

        return nil
    }
}

func frontend(w http.responsewriter, r *http.request) {
    origin, _ := url.parse("http://localhost:5000/")
    director := newdirector(*origin)
    proxy := &httputil.reverseproxy{director: director}
    proxy.servehttp(w, r)
}

func liverload_js(w http.responsewriter, r *http.request) {
    origin, _ := url.parse("http://localhost:35729/")
    director := newdirector(*origin)
    modifier := newreplacer("this.port = 35729;", "this.port = 443;")
    proxy := &httputil.reverseproxy{director: director, modifyresponse: modifier}
    proxy.servehttp(w, r)
}

func liverload_ws(w http.responsewriter, r *http.request) {
    origin, _ := url.parse("http://localhost:35729/")
    director := newdirector(*origin)
    proxy := &httputil.reverseproxy{director: director}
    proxy.servehttp(w, r)
}

func bundle_js(w http.responsewriter, r *http.request) {
    origin, _ := url.parse("http://localhost:5000/")
    director := newdirector(*origin)
    modifier := newreplacer(":35729/livereload.js?snipver=1", ":443/livereload.js?snipver=1")
    proxy := &httputil.reverseproxy{director: director, modifyresponse: modifier}
    proxy.servehttp(w, r)
}

func main() {
    http.handlefunc("/build/bundle.js", bundle_js)
    http.handlefunc("/livereload.js", liverload_js)
    http.handlefunc("/livereload", liverload_ws)
    http.handlefunc("/", frontend)
    log.fatal(http.listenandservetls(":443", "cert.pem", "key.pem", nil))
}

如果您是 install Caddy,那么您可以使用它作为您的 caddyfile

http://localhost {
    redir https://{host}{uri}
}
https://localhost {
    tls /path/to/cert.crt /path/to/cert.key
    proxy /API localhost:5000 {
            without /API
    }
    proxy / localhost:5000
}

今天关于《在Golang路由中如何集成JavaScript的热加载功能来进行开发?》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>