Go webserver on Apache

Go language allows create very easily webserver. Let’s consider a full working example of a simple web server at https://golang.org/doc/articles/wiki/ implemented in the file web8080.go:

package main

import (
    "fmt"
    "log"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}

func main() {
    http.HandleFunc("/", handler)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

Code above could be one of the several web application implemented in go language. Each application should use different port, if running on the same server. Each port could be redirected to different virtual host implemented on Apache2 webserver. For example on Ubuntu 20.04 LTS we should add apache module:
a2enmod proxy proxy_http
Create virtual host configuration file /etc/apache2/sites-available/example.com.conf

<VirtualHost *:80>
        ServerName example.com
        ProxyPass / http://127.0.0.1:8080/
        ProxyPassReverse / http://127.0.0.1:8080/

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Run command
a2ensite example.com.conf
so in the directory /etc/apache2/sites-enabled will be created symbolic link in similar way like by commands cd /etc/apache2/sites-enabled; ln -s ../sites-available/example.com.conf .
Then reload apache server
systemctl reload apache
and you should be able browse example.com and continue in development!

This entry was posted in golang, workday and tagged , , . Bookmark the permalink.

Leave a Reply