Fetch data with golang api

I am creating a blog with golang gin framework rest api. When I call the block with id, my block is displayed without error on the screen, but when I call all the blogs in the data, it gives an invalid date error

main.go:

type Blog struct {
	ID       int        `db:"id" json:"id"`
	Title    string     `db:"title" json:"title"`
	Body     string     `db:"body" json:"body"`
	ImageURL string     `db:"image" json:"image"`
	Date     *time.Time `db:"date" json:"date"`
}


// get blog by ID
	r.GET("/blog/:id", func(c *gin.Context) {
		var blog Blog
		id := c.Param("id")

		// get blog from database
		err := db.Get(&blog, "SELECT * FROM blogs WHERE id=$1", id)
		if err != nil {
			if err == sql.ErrNoRows {
				c.JSON(http.StatusNotFound, gin.H{"error": "blog not found"})
			} else {
				c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to get blog"})
			}
			return
		}

		c.JSON(http.StatusOK, blog)
	})

	// get all blogs
	r.GET("/blogs", func(c *gin.Context) {
		var blogs []Blog

		// get all blogs from database
		err := db.Select(&blogs, "SELECT * FROM blogs")
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to get blogs"})
			return
		}

		c.JSON(http.StatusOK, blogs)
	})

app.js:

useEffect(() => {
    async function fetchData() {
      try {
        const response = await axios.get('http://localhost:8000/blog/1'); //this is working

        setFirstPost(response.data);
      } catch (error) {
        setError(error.message);
      }
    }
    fetchData();

    async function fetchSecondData() {
      try {
        const response = await axios.get('http://localhost:8000/blogs');//not working

        setSecondPost(response.data);
      } catch (error) {
        setError(error.message);
      }
    }
    fetchSecondData();
  }, []);

  return (
    <div className="blog">
           <div className='blog-page'> 
                <h1> BLOG</h1>
            </div>

      {firstPost && (
        <div className="blog-first">
          <div className="blog-firstpage">
            <img src={firstPost.image} alt={firstPost.title} />
          </div>
          <div className="blog-text">
            <h2>{firstPost.title}</h2>
            <h3>{new Date(firstPost.date).toLocaleString('en-US', { dateStyle: 'medium' })}</h3>
            <p>{firstPost.body}</p>
          </div>
          
        </div>
      )}

      {secondPost && (
        <div className="blog">
          <div className="blog-secondpage">
            <img src={secondPost.image} alt={secondPost.title} />
          </div>
          <div className="blog-text">
            <h2>{secondPost.title}</h2>
            <h3>{new Date(secondPost.date).toLocaleString('en-US', { dateStyle: 'medium' })}</h3>
            <p>{secondPost.body}</p>
          </div>
         
        </div>
      )}

      {error && <p>{error}</p>}
    </div>
  );
}

export default Blog;

And the error is…
Just show it with

err := db.Select(&blogs, “SELECT * FROM blogs”)
if err != nil {
log.Println(“Error getting blogs:”, err)
c.JSON(http.StatusInternalServerError, gin.H{“error”: “failed to get blogs”})
return
}

no error it works fine but the display shows an invalid date

SELECT * FROM blogs indicates that you could fetch several rows. But your Go code indicates that only one row is fetched. And your template indicates no .range of rows is displayed.

So if you split your questions into three

  1. Does the query works in pgAdmin (or similar)? How many rows?
  2. Does Go fetches the data correct?
  3. Does the template shows the data correct? Does it iterate (.range) over the rows correctly?

Or do I miss something?

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.