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

在线运行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 ?

  • 写回答

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))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?