Module General
	EnableExplicit
	
	Procedure RespondJSON(*Request, JSON.s, Status.s = "200 OK")
		FastCGI::WriteResponseHeader(*Request, "Status",        Status)
		FastCGI::WriteResponseHeader(*Request, "Content-Type",  "application/json; charset=utf-8")
		FastCGI::WriteResponseHeader(*Request, "Cache-Control", "no-cache, no-store, must-revalidate")
		FastCGI::WriteResponseString(*Request, JSON)
		FastCGI::FinishResponse(*Request)
	EndProcedure
	
	Procedure.s GetPostField(*Request, Field.s)
		Protected PostData.s = FastCGI::GetPostData(*Request)
		Protected Count.i    = CountString(PostData, "&") + 1
		Protected i.i, Pair.s, Key.s
		For i = 1 To Count
			Pair = StringField(PostData, i, "&")
			Key  = StringField(Pair, 1, "=")
			If Key = Field
				ProcedureReturn URLDecoder(StringField(Pair, 2, "="))
			EndIf
		Next
		ProcedureReturn ""
	EndProcedure
	
	Procedure.s GetQueryField(*Request, Field.s)
		Protected QS.s    = FastCGI::GetParameter(*Request, "QUERY_STRING")
		Protected Count.i = CountString(QS, "&") + 1
		Protected i.i, Pair.s, Key.s
		For i = 1 To Count
			Pair = StringField(QS, i, "&")
			Key  = StringField(Pair, 1, "=")
			If Key = Field
				ProcedureReturn URLDecoder(StringField(Pair, 2, "="))
			EndIf
		Next
		ProcedureReturn ""
	EndProcedure
	
	Procedure ServeStatic(*Request, URI.s)
		Protected File.s
		
		If FindString(URI, "..") Or FindString(URI, "//")
			RespondJSON(*Request, ~"{\"error\":\"Forbidden\"}", "403 Forbidden")
			ProcedureReturn
		EndIf
		
		If URI = "/" Or URI = ""
			File = "www/index.html"
		Else
			File = "www" + URI
		EndIf
		
		If FileSize(File) >= 0
			If Not FastCGI::RespondFile(*Request, File)
				RespondJSON(*Request, ~"{\"error\":\"Read error\"}", "500 Internal Server Error")
			EndIf
		Else
			RespondJSON(*Request, ~"{\"error\":\"Not found\"}", "404 Not Found")
		EndIf
	EndProcedure
	
EndModule
; IDE Options = PureBasic 6.30 (Windows - x64)
; CursorPosition = 24
; Folding = h
; EnableXP
; DPIAware