Gordon Truslove
Gordon Truslove

Reputation: 784

Can I use go on a shared web server to generate 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.

Upvotes: 0

Views: 121

Answers (1)

OneOfOne
OneOfOne

Reputation: 99351

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

Example:

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.

Upvotes: 1

Related Questions