api gateway basic functionality

This commit is contained in:
gaz8860 Gary 2023-03-29 15:30:43 +01:00
parent 2a525efb4d
commit 891e565117

View File

@ -4,7 +4,6 @@ import (
"fmt" "fmt"
"log" "log"
"net/http" "net/http"
"encoding/json"
"io/ioutil" "io/ioutil"
"github.com/gorilla/mux" "github.com/gorilla/mux"
) )
@ -15,40 +14,40 @@ type Schema struct {
} }
type Container struct { type Container struct {
Id string `json:"Id`
Name string `json:"Name"` Name string `json:"Name"`
port string `json:"Port"` port string `json:"Port"`
} }
var Containers []Container
func homePage(w http.ResponseWriter, r *http.Request) { func homePage(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome to the home page!") fmt.Fprintf(w, "Welcome to the home page!")
} }
func getSchema(w http.ResponseWriter, r *http.Request){ func getSchema(w http.ResponseWriter, r *http.Request){
vars := mux.Vars(r) vars := mux.Vars(r)
container := vars["Name"] key := vars["container"]
port := vars["Port"]
requestUrl := fmt.Sprint("http://%s:%s/schema", container, port) for _, container := range Containers {
if container.Id == key {
resp, err := http.Get(requestUrl) requestURL := fmt.Sprintf("http://%s:%s/schema", container.Name, container.port)
fmt.Fprintf(w, requestURL)
resp, err := http.Get(requestURL)
if err != nil { if err != nil {
log.Fatal("Request to %s Failed: %v", container, err) log.Fatal("Request to container failed: %v", err)
} }
defer resp.Body.Close() defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body) body, err := ioutil.ReadAll(resp.Body)
if err != nil { if err != nil {
log.Fatal("error: %v", err) log.Fatal("Failed to print Body: %v", err)
} }
var response Schema fmt.Fprintf(w,string(body))
err = json.Unmarshal(body, &response) }
if err != nil {
log.Fatal("failed to unmarshal: %v", err)
} }
fmt.Println(response)
} }
@ -62,5 +61,10 @@ func handleRequests() {
} }
func main() { func main() {
Containers = []Container{
Container{Id: "1", Name: "localhost", port: "3000"},
}
handleRequests() handleRequests()
} }