dongxi3859
2018-03-22 04:37 阅读 113

在Golang中运行JavaScript代码

I need some javascript code inside go code.

package main

import (
    "fmt"
    "net/http"
)
func work(w http.ResponseWriter, r *http.Request){
    fmt.Printf("<script>console.log('javascript working')</script>")

}

func main() {
    http.HandleFunc("/", work)
    http.ListenAndServe(":4000", nil)
}

Running it in browser and see browser's console window there is nothing to see. How do I run javascript code in go code? Because using ajax with golang it is difficult.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    dougou3871 dougou3871 2018-03-22 05:52

    Very simple javascript code running in go code is

    package main
    
    import (
        "fmt"
        "net/http"
    )
    
    func main() {
        hello := "hello yu bn"
        http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
            fmt.Fprintf(w, `<html>
                <head>
                </head>
                <body>
                <h1>Go Timer (ticks every second!)</h1>
                <div id="output"></div>
                <script type="text/javascript">
                console.log("`+hello+`");
                </script>
                </body>
                </html>`)
    
        })
        http.ListenAndServe(":9000", nil)
    }
    

    it is nice! Check browser console!

    点赞 评论 复制链接分享

相关推荐