dongxiao9583
2017-01-02 05:32
浏览 115
已采纳

在线运行golang并将其保存到在线文件中

What my local program does right now is connect to a websocket and updates a local file with a json whenever a message is received.

Is there a way to run the golang program online and then update and save the file as a json file online that I will be able to see? I'm not sure but I think I would need a web server?

For example, the program would generate a website like this https://www.reddit.com/r/all.json ?

图片转代码服务由CSDN问答提供 功能建议

我的本​​地程序现在要做的是连接到Websocket,并在有消息时使用json更新本地文件 接收。

是否可以在线运行golang程序,然后将其在线更新并保存为json文件,这样我就能看到? 我不确定,但是我想我需要Web服务器吗?

例如,该程序将生成一个类似 https://www.reddit.com/r/all.json

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongsha1544 2017-01-02 05:51
    已采纳

    Typically most websites generate JSON responses directly into the HTTP request, they don't write the results into a file that is then served over HTTP.

    You will need some kind of server that is exposed to the Internet either way. I would recommend you reading about how to use the HTTP server built into Go, so you don't need to write the results into a file: https://golang.org/doc/articles/wiki/. Once you gain a better understand on how web applications work, you can use higher level web frameworks that can help you be more productive, such as gin: https://github.com/gin-gonic/gin.

    If you would still really like to write the results in a file and serve that file, you may as well use Go as the web server, and use https://golang.org/pkg/net/http/#ServeFile.

    Example code of doing this:

    package main
    
    import (
        "log"
        "net/http"
    )
    
    func main() {
        http.HandleFunc("/myfile.json", func(w http.ResponseWriter, r *http.Request) {
            http.ServeFile(w, r, "path/to/myfile.json")
        })
    
        // Serve on HTTP port (80)
        log.Fatal(http.ListenAndServe(":80", nil))
    }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题