Browse Source

Add simple server

Robin de Jong 11 months ago
commit
92a3289639
2 changed files with 70 additions and 0 deletions
  1. 67 0
      main.go
  2. 3 0
      run.sh

+ 67 - 0
main.go

@@ -0,0 +1,67 @@
+package main
+
+import (
+	"fmt"
+	"log"
+	"math/rand"
+	"net/http"
+)
+
+var items = [...]string{"EMF Reader", "Lighter", "UV Light", "Crucifix", "Video Camera", "Spirit Box", "Salt", "Smudge Sticks", "Tripod", "Motion Sensor", "Sound Sensor", "Thermometer", "Sanity Pills", "Ghost Writing Book", "Infrared Light Sensor", "Parabolic Microphone", "Glowsick", "Head Mounted Camera"}
+var used = []string{}
+
+func item(w http.ResponseWriter, r *http.Request) {
+	str := ""
+	item := get()
+	if item == nil {
+		str = "No items left"
+	} else {
+		str = fmt.Sprint("[", len(used), "] ", *item)
+	}
+
+	w.Write([]byte(str))
+}
+
+func reset(w http.ResponseWriter, r *http.Request) {
+	used = []string{}
+	str := "Resetted!"
+	w.Write([]byte(str))
+}
+
+func get() *string {
+	if len(items) == len(used) {
+		return nil
+	}
+
+	item := randomItem()
+	for ok := true; ok; ok = contains(item, used) {
+		item = randomItem()
+	}
+	used = append(used, item)
+	return &item
+}
+
+func randomItem() string {
+	size := len(items)
+	return items[rand.Intn(size)]
+}
+
+func contains(str string, arr []string) bool {
+	for _, obj := range arr {
+		if obj == str {
+			return true
+		}
+	}
+
+	return false
+}
+
+func main() {
+	http.HandleFunc("/item", item)
+	http.HandleFunc("/reset", reset)
+
+	log.Printf("Starting server on port 8080...\n")
+	if err := http.ListenAndServe(":8080", nil); err != nil {
+		log.Fatal(err)
+	}
+}

+ 3 - 0
run.sh

@@ -0,0 +1,3 @@
+#!/bin/bash
+
+go run main.go