{"movies":[{"id":1,"title":"Moana","year":,"runtime":"mins","genres":["animation","adventure"],"version":1},{"id":2,"title":"BlackPanther","year":,"runtime":"mins","genres":["sci-fi","action","adventure"],"version":2}...etc]}更新应用程序为了从PostgreSQL数据库中查询这些数据,让我们在数据库模型中创建一个新的GetAll()方法,它执行以下SQL查询:
SELECTid,created_at,title,year,runtime,genres,versionFROMmoviesORDERBYid因为我们期望这个SQL查询返回多条记录,所以需要使用Go的QueryContext()方法来运行它。如下所示:File:internal/data/movies.go
//GetAll()返回movies切片func(mMovieModel)GetAll(titlestring,genres[]string,filtersFilters)([]*Movie,error){query:=`SELECTid,create_at,title,year,runtime,genres,versionFROMmoviesORDERBYid`//创建3s超时上下文实例ctx,cancel:=context.WithTimeout(context.Background(),3*time.Second)defercancel()//使用QueryContext()来执行查询rows,err:=m.DB.QueryContext(ctx,query)iferr!=nil{returnnil,err}deferrows.Close()//初始化切片,用户存储查询结果movies:=[]*Movie{}forrows.Next(){varmovieMovieerr:=rows.Scan(movie.ID,movie.CreateAt,movie.Title,movie.Year,movie.Runtime,pq.Array(movie.Genres),movie.Version,)iferr!=nil{returnnil,err}movies=append(movies,movie)}//rows.Next()循环结束,调rows.Err()查看是否迭代过程中发送错误iferr=rows.Err();err!=nil{returnnil,err}returnmovies,nil}接下来,我们需要调整listMoviesHandler,以便它调用新的GetAll()方法来检索电影数据,然后将该数据作为JSON响应写入。更新接口处理程序如下所示:File:cmd/api/movies.go
packagemain...func(app*application)listMoviesHandler(w