Hamburger
Hub
goAPI

The Web client

This site is example of a simple web client. Or web site. Check out Topics and Users to see the fetched result from Postgresql. The Go code to manage this simple web client and fetching data from the Postgresql server is below. Note that this code replaces Apache/Nginx, Node.js and PHP just in a few magic lines. The enging of this site is just under 10 MB of compiled code (+ common html templates, CSS, Javascript, images etc)

package main

import (
  "encoding/json"
  "html/template"
  "log"
  "net/http"
  "strings"
)

var tpl *template.Template

func init() {
  tpl = template.Must(template.ParseGlob("public/tmpl/*.html"))
  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"))))
}

// Go web server (replaces Apache/Nginx) and a endpoint server.
func main() {
  http.HandleFunc("/", endpoint)
  log.Fatal(http.ListenAndServe(":6060", nil))
}

// Dynamic endpoints based on url paths
func endpoint(w http.ResponseWriter, r *http.Request) {
  path := strings.Trim(r.URL.Path, "/")
  page := (path + ".html")
  url := ("http://94.237.92.101:6061/" + path)
  //url := ("http://127.0.0.1:6061/" + path)
  switch path {
  case "favicon.ico", "robots.txt":
    return
  case "": // no endpoint
    page = "home.html"
    fallthrough
  default:
    //if template not found -> redirect.go
    exist := tpl.Lookup(page)
    if exist == nil {
      logg("not found")
      redirect(w, r)
      return
    }
    // get data and fill template
    data := json2map(url)
    tpl.ExecuteTemplate(w, page, data)
  }
}

func json2map(url string) interface{} {
  // call the API and get body
  resp, err := http.Get(url)
  if err != nil {
    logg(err.Error())
  }
  defer resp.Body.Close()

  // json to map
  var result interface{}
  err = json.NewDecoder(resp.Body).Decode(&result)
  if err != nil {
    logg(err.Error())
  }

  return (result)
}