英文:
Can I use go on a shared web server to generate HTML?
问题
通常我使用C#来进行所有的工作,我可以使用C#创建桌面应用程序,并且还可以将大量相同的C#代码放在我的共享托管Web服务器上的一个dll中。这样可以节省很多编码时间。
是否有办法在Go中实现这个功能呢?
例如,在我的托管Web服务器上放置一种类似于Go的dll来生成HTML。
我知道Go不支持dll,我也知道使用Go创建一个监听端口80的Web服务器很简单。但这对于共享Web服务器来说并不是一个解决方案。
这似乎是Go的一个很好的用途,让我感到惊讶的是这似乎不可能实现。
我应该提到,如果Go代码不必在每个HTTP请求时重新启动,那将会很好。
以下是我在C#中的做法:
在Web服务器上,我添加一个像这样的aspx页面:
<%@ Page Language="C#" %>
<%@ Register TagPrefix="MyDLL" Namespace="MyDLL" Assembly="MyDLL"%>
<MyDLL:Web Runat="Server"/>
它只是加载了一个C#的dll,该dll根据HTTP请求生成HTML。
英文:
Normally I use C# for everything, I can create a desktop application with C# and also place a lot of the same c# code in a dll on my shared hosted web server. This saves me a lot of coding time.
Is there any way to this with go?
e.g. place some kind of go dll on my hosted web server to generate HTML.
I am aware that go doesn't do dll's, I am also aware that creating a web server with go to listen to port 80 is straight forward. But this is not a solution for a shared web server.
This seems like a brilliant use for go and it surprises me that this might not be possible.
I should mention, it would be nice if the go code didn't have to restart with every http request.
This is how I do it with C#:
On the web server I add an aspx page like this:
<%@ Page Language="C#" %>
<%@ Register TagPrefix="MyDLL" Namespace="MyDLL" Assembly="MyDLL"%>
<MyDLL:Web Runat="Server"/>
It simply loads the C# dll which generates HTML based on the http request.
答案1
得分: 1
首先,您需要设置IIS来使用FastCGI(说明),然后您可以像通常一样构建一个Go Web应用程序,但是不使用http.ListenAndServe
,而是使用fcgi.Serve
。
示例代码如下(示例):
func hello(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "Hello, world of FCGI!")
}
func main() {
http.HandleFunc("/hello/", hello)
if err := fcgi.Serve(nil, nil); err != nil {
log.Fatal("fcgi.Serve: ", err)
}
}
但请记住,可能会有多个实例的程序一直在运行/销毁,因此任何临时数据(内存会话等)应存储在memcache、临时文件或数据库中。
英文:
First you have to setup IIS to use fastcgi (instructions) then you can simply build a go web app like you normally would but instead of using http.ListenAndServe you use fcgi.Serve
func hello(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "Hello, world of FCGI!")
}
func main() {
http.HandleFunc("/hello/", hello)
if err := fcgi.Serve(nil, nil); err != nil {
log.Fatal("fcgi.Serve: ", err)
}
}
But keep in mind that there can be multiple instances of the programming running / destroyed all the time, so any temp data (in-memory sessions, etc) should be stored on memcache or temp files on disk or a database.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论