登录
首页 >  Golang >  Go问答

如何解决结构中持久数据问题并获取最新数据实例?

来源:stackoverflow

时间:2024-03-12 23:51:29 255浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《如何解决结构中持久数据问题并获取最新数据实例?》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

问题内容

我有这个微服务,可以为用户准备数据以通过 api 路径检索。

但是,在用户获取请求的数据之前,我需要进行一些数据处理。我就是这样做的:

我将包含数据的填充结构传递给两个函数,用于处理 getdataoriginweather()getdatadestinationweather()。这两个函数运行后,api 服务器可供用户请求数据(也称为结构体)。

问题是,用户提取的结构包含通过这两个函数处理数据之前和之后的记录的混合。

结构体的预期数据只能是通过两个函数传递后的数据。

我正在将此结构从一个包传递到另一个包。

这是我的代码。

// the struct i'm working with and that will eventually be get requested by users.
package models

type travelitenaries struct {
    origin                string
    destination           string
    flight_num            string
    origin_latitude       string
    origin_longitude      string
    destination_latitude  string
    destination_longitude string
    coordinates_ori       string
    coordinates_dest      string
    temp_c_ori            string
    temp_f_ori            string
    temp_c_dest           string
    temp_f_dest           string
    lastupdated           string
}

这是我在允许将数据发送给用户之前处理数据的地方。

package data

// for brevity i have removed how i populated the struct. i do so by using a csv file. 

func getdataoriginweather() (travel *models.travelitenaries, err error) {
    fmt.println("getting origin data from weather api...")
    // construct url params for weather api calls.
    params := url.values{
        "key": []string{"xxx"},
        "q":   []string{""},
    }

    // build url for request
    u := &url.url{
        scheme: "https",
        host:   "api.weatherapi.com",
        path:   "/v1/current.json",

        // encode params for url syntax
        rawquery: params.encode(),
    }

    client := &http.client{}

    values := u.query()
    var responsedata models.originweather
    for _, flight := range travelitenaries {
        values.set("q", flight.coordinates_ori)
        u.rawquery = values.encode()
        req, err := http.newrequest("get", u.string(), nil)
        if err != nil {
            fmt.println(err)
        }

        resp, err := client.do(req)
        if err != nil {
            fmt.println(err)
        }
        defer resp.body.close()
        body, err := ioutil.readall(resp.body)
        if err != nil {
            fmt.println(err)
        }

        json.unmarshal(body, &responsedata)
        flight.temp_f_ori = strconv.formatfloat(responsedata.current.temp_f_ori, 'g', -1, 64)
        flight.temp_c_ori = strconv.formatfloat(responsedata.current.temp_c_ori, 'g', -1, 64)
        flight.lastupdated = responsedata.current.lastupdated
        //fmt.println(utils.prettyprint(flight))
        travelitenaries = append(travelitenaries, flight)
    }
    
    return travel, nil

}

// run processes the data for me.
func run() {
    fmt.println("starting weather api requests...")
    getdatadestinationweather() // note that for brevity, i won't preset  getdatadestinationweather() here because it's basically the exact same function as the one below
    getdataoriginweather() // this function and getdatadestinationweather() work on the same struct. 
    fmt.println("completed weather api requests... \n...data loaded & ready.")
}

对我来说,问题是在 getdatadestinationweather()getdataoriginweather() 处理后,将此结构传递到我的 handlers 包,其中包含预期数据

package handlers 

// as you see I'm using a pointer, assuming my problems would be solved. 
// for the most part this does everything I want, except that I'm also getting 
// records in my struct from before it's been processed by getDataOriginWeather()
// and getDataDestinationWeather()
var Data = &data.TravelItenaries

func (s *Server) getWeather(w http.ResponseWriter, r *http.Request) {
    ...
    // Here I'm simply trying to print the struct to the user after it's been processed
    // by data.getDataOriginWeather() and data.getDataDestinationWeather with the expected 
    // data. 
    fmt.Println(utils.PrettyPrint(Data))

}

虽然 var data = &data.travelitenaries 确实包含“预期数据”,但它还包含函数之前的旧记录。

data.run() 中处理该结构后,如何将处理后的数据显式传递给 handlers.getweather() 。我在这里使用指针提供了混合结果。

如果您需要查看我的更多代码,请告诉我。


正确答案


在“运行”功能中,您似乎是:

  • 不检查错误 - 我认为你应该这样做。
  • 使用可变的全局变量 - 如果不这样做,您的代码将会更干净、更容易测试和调试。

如何在结构体中处理后显式传递该结构体 data.run() 到 handlers.getweather() 以及处理后的数据。我的使用 这里的指针提供了混合结果。

创建一个包含处理调用所需内容的结构。为该结构实现 http.handler 。在设置服务器时使用它。

示例:

package main

import (
    "encoding/json"
    "log"
    "net/http"
)

type TravelHandler struct {
    Data interface{} // the preloaded data you need to serve http
}

func (th TravelHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    err := json.NewEncoder(w).Encode(th.Data)

    if err != nil {
        http.Error(w, "could not encode data", 500)
    }
}

func createTravelHandler() *TravelHandler {
    // populate travel handler

    return &TravelHandler{}
}

func main() {
    th := createTravelHandler() // no mutable global, return the handler from a function (or pipe it through several functions)

    err := http.ListenAndServe("localhost:3000", th)

    log.Println(err)
}

终于介绍完啦!小伙伴们,这篇关于《如何解决结构中持久数据问题并获取最新数据实例?》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>