package main

import (
	"log"
	"net/http"
	"strings"
)

func runServer() {
	address := config.Host + ":" + config.Port
	http.HandleFunc("/", route)
	log.Println("Serving content at 'http://" + address + "'.")
	log.Fatal(http.ListenAndServe(address, nil))
}

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

	tab := routingTable{
		{"/favicon.ico", "GET", staticGet("favicon.ico")},
		{"/static/style.css", "GET", staticGet("style.css")},
		{"/add_recipes", "GET", addRecipesGet},
		{"/recipe/confirm-deletion", "GET", recipeConfirmDeletionGet},
		{"/recipe/confirm-deletion", "POST", recipeConfirmDeletionPost},
		{"/recipe/edit", "GET", recipeEditGet},
		{"/recipe/edit", "POST", recipeEditPost},
		{"/recipe", "GET", recipeGet},
		{"/", "GET", indexGet},
	}

	for _, v := range(tab) {
		if strings.HasPrefix(r.URL.String(), v.target) && r.Method == v.method {
			v.handler(w, r)
			return
		}
	}

	http.Error(w, "Bad Request", 400)
}

type routingTable []struct {
	target string
	method string
	handler func(w http.ResponseWriter, r *http.Request)
}