mc_man/util/webserver.go

127 lines
2.5 KiB
Go

package util
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
)
var output_channel chan string
func StartServer(ch chan string) {
output_channel = ch
_, err := os.Stat("mapcrafter/index.html")
if err == nil {
// Looks like mapcrafter is present
output_channel <- "* Mapcrafter Directory is Present, routing to /map\n"
fs := http.FileServer(http.Dir("mapcrafter"))
http.Handle("/map/", http.StripPrefix("/map/", fs))
}
http.HandleFunc("/api/", serveAPI)
http.HandleFunc("/", serveMcMan)
http.ListenAndServe(":8080", nil)
}
func serveMcMan(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, htmlHeader("mc_man - Minecraft Manager"))
fmt.Fprintf(w, "Hey-o! It's the manager!")
fmt.Fprintf(w, htmlFooter())
}
func serveAPI(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
if err != nil {
panic(err)
}
if err := r.Body.Close(); err != nil {
panic(err)
}
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
// What are we doing with this request?
output_channel <- fmt.Sprint("HTTP Request: (", r.Method, ") ", r.URL, "\n")
the_path = r.URL.Path
output_string = ""
if strings.HasPrefix(the_path, "/api") {
the_path = strings.TrimPrefix(the_path, "/api")
if strings.HasPrefix(the_path, "/v1") {
the_path = strings.TrimPrefix(the_path, "/v1")
if strings.HasPrefix(the_path, "/whitelist") {
output_string = handleWhitelist(r)
} else if strings.HasPrefix(the_path, "/ops") {
output_string = handleOps(r)
}
}
}
}
/* JSON Functions */
func handleOps(r *http.Request) string {
if r.Method == "GET" {
return getOps()
} else if r.Method == "POST" {
// Add posted user to Ops
}
return ""
}
func handleWhitelist(r *http.Request) string {
if r.Method == "GET" {
return getWhitelist()
} else if r.Method == "POST" {
// Add posted user to whitelist
}
return ""
}
func getOps() string {
ret := "["
num_users := 0
for _, op_user := range GetConfig().Ops {
if num_users > 0 {
ret += ","
}
ret += fmt.Sprint("\"", op_user, "\"")
}
ret += "]"
return ret
}
func getWhitelist() string {
ret := "["
num_users := 0
for _, wl_user := range GetConfig().Whitelist {
if num_users > 0 {
ret += ","
}
ret += fmt.Sprint("\"", wl_user, "\"")
}
ret += "]"
return ret
}
/* HTML Functions */
func htmlHeader(title string) string {
head := `
<!DOCTYPE html>
<html>
<head>
<title>`
head += title
head += `
</title>
</head>
<body>
`
return head
}
func htmlFooter() string {
return `
</body>
</html>
`
}