Browse Source

Add CORS header param

master
NGnius 4 years ago
parent
commit
76c6355894
3 changed files with 18 additions and 4 deletions
  1. +1
    -0
      config.go
  2. +12
    -4
      handlers.go
  3. +5
    -0
      sql_service.go

+ 1
- 0
config.go View File

@@ -26,6 +26,7 @@ func initArgs() {
flag.BoolVar(&buildTables, "build-db", false, "Build database tables on startup")
flag.BoolVar(&populateTables, "populate-db", false, "Populate database with test data")
flag.BoolVar(&randomizeTokens, "random-tokens", false, "Generate tokens with some random bytes")
flag.StringVar(&corsHeader, "cors-header", defaultCorsHeader, "Access-Control-Allow-Origin HTTP request header")
}

func parseArgs() {


+ 12
- 4
handlers.go View File

@@ -12,9 +12,17 @@ import (
"strings"
)

const (
defaultCorsHeader = "*"
)

var (
corsHeader string
)

func boardHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
w.Header().Add("Access-Control-Allow-Origin", "*")
w.Header().Add("Access-Control-Allow-Origin", corsHeader)
if r.Method != "GET" {
//w.WriteHeader(405)
errorResponse(405, "Non-GET method not allowed at this endpoint", w, r)
@@ -76,7 +84,7 @@ func boardHandler(w http.ResponseWriter, r *http.Request) {

func playerHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
w.Header().Add("Access-Control-Allow-Origin", "*")
w.Header().Add("Access-Control-Allow-Origin", corsHeader)
if r.Method != "GET" {
//w.WriteHeader(405)
errorResponse(405, "Non-GET method not allowed at this endpoint", w, r)
@@ -131,7 +139,7 @@ func playerHandler(w http.ResponseWriter, r *http.Request) {

func newEntryHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
w.Header().Add("Access-Control-Allow-Origin", "*")
w.Header().Add("Access-Control-Allow-Origin", corsHeader)
if r.Method != "POST" {
//w.WriteHeader(405)
errorResponse(405, "Non-POST method not allowed at this endpoint", w, r)
@@ -183,7 +191,7 @@ func newEntryHandler(w http.ResponseWriter, r *http.Request) {

func newKeyHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
w.Header().Add("Access-Control-Allow-Origin", "*")
w.Header().Add("Access-Control-Allow-Origin", corsHeader)
if r.Method != "POST" {
errorResponse(405, "Non-POST method not allowed at this endpoint", w, r)
return


+ 5
- 0
sql_service.go View File

@@ -98,6 +98,11 @@ func keyByToken(token string) (*Key, error) {
return k, db.QueryRow("SELECT * FROM Keys WHERE token=? LIMIT 1;", token).Scan(k.Intake()...)
}

func keyByPlayer(player int64) (*Key, error) {
k := &Key{}
return k, db.QueryRow("SELECT * FROM Keys WHERE player=? LIMIT 1;", player).Scan(k.Intake()...)
}

// internal operations
func sqlBuildTables() {
transaction, txErr := db.Begin()