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

报告相同问题?

悬赏问题

  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化