Go backend for tracking results from conway game of life soup search.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

114 lines
2.2 KiB

package main
import (
"net/http"
"github.com/gorilla/mux"
"fmt"
"encoding/json"
)
type SpeciesResp struct {
Name string
FirstFound int
LastFound int
Population int
Examples []string
Hashes []string
}
// Returns first and last found of species, a list of "example soups" for the user to see in browser and the complete list of soups recorded in the db
func GetSpecies(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
species := vars["species"]
genus := vars["genus"]
family := vars["family"]
// Start collecting data from sql db
apgcode := family + genus + "_" + species
life, err := SQLGetLife(apgcode)
if err != nil {
panic(err)
}
samples, err := SQLGetSamples(apgcode)
if err != nil {
panic(err)
}
// Examples should be the first found and the lastfound,
// if the first found is the last found than skip it
var examples []string
if len(samples) == 1 {
examples = append(examples, samples[0].Hash)
} else {
examples = append(examples, samples[0].Hash)
examples = append(examples, samples[len(samples) - 1].Hash)
}
// Get list of all found hashes
hashes := make([]string, len(samples))
for i, s := range samples {
hashes[i] = s.Hash
}
ret := SpeciesResp{
Name: life.Apgcode,
FirstFound: life.FirstFound,
LastFound: life.LastFound,
Population: life.Population,
Examples: examples,
Hashes: hashes,
}
b, err := json.Marshal(ret)
if err != nil {
panic(err)
}
fmt.Fprintf(w, "%s", string(b))
}
// Returns list of species in a genus ordered by population
func GetGenus(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
genus := vars["genus"]
family := vars["family"]
apgcode := family + genus
ret, err := SQLGetGenus(apgcode)
if err != nil {
panic(err)
}
// No processing is needed here so we just send the json
b, err := json.Marshal(ret)
if err != nil {
panic(err)
}
fmt.Fprintf(w, "%s", string(b))
}
func GetFamily(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
family := vars["family"]
ret, err := SQLGetFamily(family)
if err != nil {
panic(err)
}
// No processing is needed here so we just send the json
b, err := json.Marshal(ret)
if err != nil {
panic(err)
}
fmt.Fprintf(w, "%s", string(b))
}