1
\$\begingroup\$

My intention is to create an API as generic and DRY as possible using Go. To achieve this, I have made some more or less common decisions:

  1. To use AJAX call to avoid reloading page when updating the web page. Instead of using Go.
  2. To exclude hard coded queries from the API to reduce the endpoints (routes). As a bonus the queries can be modified without recompile the API when updating queries
  3. To use JSON to create and update data to get it more generic.
  4. To use the sqlx driver in order to further reduce code and avoid repeating.

enter image description here

My questions are:

  1. Can you see any security issues? (Except CORS)
  2. Anything you should done different?
  3. Any thoughts about the generic approach?
package main

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

var db *sqlx.DB

func main() {
  Connect()
  http.HandleFunc("/", handler)
  http.Handle("/favicon.ico", http.NotFoundHandler())
  http.ListenAndServe(":9998", nil)
}

func handler(w http.ResponseWriter, r *http.Request) {

  w.Header().Set("Access-Control-Allow-Origin", "*")
  w.Header().Set("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT,CREATE,DELETE")
  w.Header().Set("Access-Control-Allow-Headers", "*")
  w.Header().Set("Content-Type", "application/json")

  switch r.Method {
  case "DELETE":
    Delete(w, r)
  case "POST":
    Create(w, r)
  case "PUT":
    Update(w, r)
  default: //GET
    Get(w, r)
  }
}

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 getpath(r *http.Request) (string, string, string) {
  path := strings.Split(r.URL.String(), "/")
  switch len(path) {
  case 4:
    return path[1], path[2], path[3]
  case 3:
    return path[1], path[2], ""
  case 2:
    return path[1], "", ""
  default:
    return "", "", ""
  }
}

More detailed description is here: https://crud.go4webdev.org/api3rest

\$\endgroup\$
3
  • \$\begingroup\$ All the code you want reviewed must be included in the body of the question. \$\endgroup\$ Commented Feb 17, 2022 at 15:26
  • \$\begingroup\$ @pacmaninbw Thanks for letting me know. \$\endgroup\$ Commented Feb 17, 2022 at 19:05
  • \$\begingroup\$ Which computer science / programming Stack Exchange sites do I post on? \$\endgroup\$ Commented Feb 18, 2022 at 9:31

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.