Hub
Menu
Sub navigation

Build the Go Web Server

This simple code in "main.go" replaces both Apache/Nginx and PHP. The code below is the heart of the Go Web Server of this site. This code also dynamically handles endpoints and redirects.

package main

import (
  "html/template"
  "net/http"
  "strings"
)

var tpl *template.Template

func init() {
  tpl = template.Must(template.ParseGlob("public/tmpl/*.html"))
  http.Handle("/img/", http.StripPrefix("/img/", http.FileServer(http.Dir("./public/img"))))
  http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("./public/css"))))
  http.Handle("/icn/", http.StripPrefix("/icn/", http.FileServer(http.Dir("./public/icn"))))
  http.Handle("/js/", http.StripPrefix("/js/", http.FileServer(http.Dir("./public/js"))))
  http.Handle("/mov/", http.StripPrefix("/mov/", http.FileServer(http.Dir("./public/mov"))))
}

func main() {
  http.HandleFunc("/", endpoint)
  http.Handle("/favicon.ico", http.NotFoundHandler()) //????????)
  http.ListenAndServe(":9091", nil)
}

func endpoint(w http.ResponseWriter, r *http.Request) {
  path := strings.Trim(r.URL.Path, "/")
  page := (path + ".html")

  switch path {
  case "contactme":
    contactme(w, r)
  case "": //empty
    url := geturl(path)
    w.Header().Add("Vary", "Accept-Encoding")
    w.Header().Set("Cache-Control", "max-age=3600")
    w.Header().Set("Access-Control-Allow-Origin", "*")
    tpl.ExecuteTemplate(w, "home.html", url)
  default:
    w.Header().Add("Vary", "Accept-Encoding")
    w.Header().Set("Cache-Control", "max-age=3600")
    w.Header().Set("Access-Control-Allow-Origin", "*")
    exist := tpl.Lookup(page)
    if exist == nil {
      redirect(w, r) // if not found -> redirect.go
    }
    url := geturl(path)
    tpl.ExecuteTemplate(w, page, url)
  }
}

func geturl(path string) string {
  //used for canonical path on each page
  switch path {
  case "":
    return ("https://static.go4webdev.org/")
  default:
    return ("https://static.go4webdev.org/" + path)
  }
}