我目前正在針對返回批處理結果的 xml 服務進行編寫。我目前有以下幾點:type QueryEnvelope struct { XMLName xml.Name `xml:"http://schemas.xmlsoap.org/soap/envelope/ Envelope"` Body *QueryBody `xml:"http://schemas.xmlsoap.org/soap/envelope/ Body"`}type QueryBody struct { QueryResult *QueryResult `xml:"queryResponse>result"`}type QueryResult struct { QueryLocator QueryLocator `xml:"queryLocator"` Done bool `xml:"done"` Size int `xml:"size"` Records interface{} `xml:"records"`}type QueryLocator stringfunc (r *Resource) Query(sql string, r interface{}) error { // builds xml request // sends xml request through Resource which contains the net client // decodes the result into r (type for records in QueryResult)}func (r *Resource) QueryMore(q QueryLocator, r interface{}) error { // same as above except takes queryLocator and makes call to different endpoint in order to continue retrieving results, when QueryResult.Done == true, done fetching results}顯然這需要重構,因為客戶端需要查看是否 Done == true 以便他們可以繼續獲取。我正在考慮添加以下內容,并將 Query 和 QueryMore 移動為 Querier 的一種方法:type Querier struct { r *Resource Done bool QueryLocator QueryLocator }func New(r *Resource) *查詢器{}客戶端然后會這樣表現:err := q.Query("sql statement", r)if err != nil { // handle}// do stuff with rfor q.Done == false { q.QueryMore(r) // do stuff with r}我想知道這里的慣用方法是什么,以便最好地“流式傳輸”結果。
1 回答

呼喚遠方
TA貢獻1856條經驗 獲得超11個贊
一種選擇是使用 stdlibsql包用于遍歷行的模式。通過這種方式,您可以將初始查詢與后續調用統一起來。
有一個Next()方法,它用查詢結果填充內部結構,true如果有結果未決則返回。在您的情況下,您仍然需要一個初始構造函數,例如Query,但這只會設置數據結構。調用才是Next()真正的工作,而調用Scan(r)(或任何你想調用的讀取結果的方法)只是呈現給結果。迭代完成后,您就有了Err()檢查任何操作錯誤的方法。
稍微改變 sql 包中的示例:
// setup the query, but delay any action until we start iterating.
query, err := NewQuery(queryParameters)
// check err of course
defer query.Close()
for query.Next() {
err = query.Scan(&r)
...
}
err = query.Err() // get any error encountered during iteration
您還可以查看其他驅動程序,例如mgo此模式的變體。
- 1 回答
- 0 關注
- 223 瀏覽
添加回答
舉報
0/150
提交
取消