Template DataBase RestApi

Does anyone have any examples on how to connect backend and fronted please?

I know I need to send data using:

template.ExecuteTemplate(w, "index/html, data)

But I created my Api using MongoDB and I don’t know how to do it right :frowning:

I just want to send that JSON to the front, I tried for example some func:

r , err := htpp.Get("localhost:3000/users")

if err != nil { 
            panic (err)
          }

defer r.Body.Close()

body, err := io.ReadAll(r.Body)

if err != nil { 
            panic (err)
          }

var users [ ]models.User = make([ ]models.User, 0)

json.Unmarshal(body, &users)
       
template.ExecuteTemplate(w, "index/html, users)

fmt.Println(string(body)) //here I have the correct data
fmt.Println(users) //I have no data here
  • Check the error return from json.Unmarshal.
  • You probably have a mismatch between your models.User struct definition and the json body structure.
1 Like

I already managed to fix it, the problem was stupid haha I had some errors in the structure and also when I handled the Unmarshal error I could see that I was getting an array and saving it wrong. Thank you very much bro!