Go API
goAPI

The API Server

API is an separate server listening on port 6061 that servers basically CRUD requests. The experimental code is below. The API can be called from anywhere. From the Go code, from AJAX or any partner outside. The advantage of AJAX is that not whole page has to be reloaded. And there are fewer calls involved.

package main

import (
  "encoding/json"
  "fmt"
  "github.com/jmoiron/sqlx"
  _ "github.com/lib/pq"
  "log"
  "net/http"
  "strings"
)

var db *sqlx.DB

func main() {
  Connect()
  http.HandleFunc("/", endpoint)
  http.ListenAndServe(":6061", nil)
}

func endpoint(w http.ResponseWriter, r *http.Request) {
  path := strings.Trim(r.URL.Path, "/")
  var data interface{}

  switch path {
  case "favicon.ico", "robots.txt":
    return
  default:
    query := Getquery(path)
    data = (Get(query))
    // convert to json and write
    json.NewEncoder(w).Encode(data)
  }
}

func Getquery(path string) string {
  // get query from lookup db
  var query string
  err := db.QueryRow("SELECT sql_query FROM sqls WHERE sql_id=$1", path).Scan(&query)
  if err != nil {
    path = ""

  }
  return query
}

func Get(query string) interface{} {
  // execute query to postgresql db
  if len(query) > 0 {
    var list []map[string]interface{}
    rows, err := db.Queryx(query)

    if err != nil {
      fmt.Println("no records")
    }

    defer rows.Close()

    for rows.Next() {
      row := make(map[string]interface{})
      err = rows.MapScan(row)
      if err != nil {
        log.Fatal(err)
      }
      list = append(list, row)
    }

    rows.Close()
    if len(list) == 0 {
      return ("norec")
    }
    return list
  }
  return nil
}