英文:
Run golang online and save it to an online file
问题
我目前的本地程序是连接到一个 WebSocket,并在接收到消息时更新一个本地文件的 JSON。
有没有办法在线运行 golang 程序,然后将文件更新并保存为一个在线的 JSON 文件,以便我能够查看?我不确定,但我认为我需要一个 Web 服务器?
例如,程序会生成一个类似于 https://www.reddit.com/r/all.json 的网站吗?
英文:
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
得分: 0
通常,大多数网站会直接将JSON响应生成到HTTP请求中,而不是将结果写入文件然后通过HTTP提供服务。
无论如何,您都需要一个向互联网公开的服务器。我建议您阅读有关如何使用Go内置的HTTP服务器的文章,这样您就不需要将结果写入文件:https://golang.org/doc/articles/wiki/。一旦您对Web应用程序的工作原理有了更好的理解,您可以使用更高级的Web框架来提高生产力,例如gin:https://github.com/gin-gonic/gin。
如果您仍然希望将结果写入文件并提供该文件,您可以使用Go作为Web服务器,并使用https://golang.org/pkg/net/http/#ServeFile。
以下是执行此操作的示例代码:
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")
})
// 在HTTP端口(80)上提供服务
log.Fatal(http.ListenAndServe(":80", nil))
}
请注意,您需要将"path/to/myfile.json"替换为实际文件的路径。
英文:
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))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论