package api import ( "net/http" "strconv" "velvettear/badger/internal/config" "velvettear/badger/internal/library" "velvettear/badger/internal/log" ) // exported function(s) func StartServer() { serverAddress := config.ApiListen() + ":" + strconv.Itoa(config.ApiPort()) registerEndpoints() log.Info("starting the api server", "address: '"+serverAddress+"'") error := http.ListenAndServe(serverAddress, nil) if error != nil { log.Fatal("encountered an error starting the api server", error.Error()) } } // unexported function(s) func registerEndpoints() { endpoint{ address: "/library/update", async: false, function: library.Update, }.register() endpoint{ address: "/library/import", async: false, function: library.Import, }.register() endpoint{ address: "/library/duplicates", async: false, function: library.FindDuplicates, }.register() } func (endpoint endpoint) register() { log.Debug("registering api endpoint '" + endpoint.address + "'...") http.HandleFunc(endpoint.address, func(response http.ResponseWriter, request *http.Request) { log.Debug("called api endpoint '" + endpoint.address + "'...") if !runBlocking(endpoint.address) { response.Write([]byte("function '" + getRunning().functionName + "' is already running")) response.WriteHeader(503) } state := getRunning() msg := "function '" + state.functionName + "'" if endpoint.async { go endpoint.function.(func())() msg += " started asynchronously" } else { endpoint.function.(func())() msg += " finished after " + strconv.Itoa(int(finish().Milliseconds())) + "ms" } response.Write([]byte(msg)) }) } // struct(s) type endpoint struct { address string async bool function interface{} }