gpt4 book ai didi

rest - 如何使用 Mutex 字段创建结构的元素

转载 作者:数据小太阳 更新时间:2023-10-29 03:39:15 26 4
gpt4 key购买 nike

我有一个 Get()功能:

func Get(url string) *Response {
res, err := http.Get(url)
if err != nil {
return &Response{}
}
// res.Body != nil when err == nil
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Fatalf("ReadAll: %v", err)
}
reflect.TypeOf(body)
return &Response{sync.Mutex(),string(body), res.StatusCode}
}

以及 Read()功能:

func Read(url string, timeout time.Duration) (res *Response) { 
done := make(chan bool)

go func() {
res = Get(url)
done <- true
}()
select { // As soon as either
case <-done: // done is sent on the channel or
case <-time.After(timeout): // timeout
res = &Response{"Gateway timeout\n", 504}

}
return
}

Response函数返回的类型定义为:

type Response struct {
Body string
StatusCode int
}

这个读取函数使用了 Get()功能,还实现了超时。问题是如果发生超时并且 Get() 可能会发生数据竞争。响应写入 res同时在Read() .

我有一个解决这个问题的计划。就是用Mutex。为此,我将向 Response 添加一个字段结构:

type Response struct {
mu sync.Mutex
Body string
StatusCode int
}

这样 Response可以上锁。但是,我不确定如何在代码的其他部分修复此问题。

对于 Get(),我的尝试看起来像这样:

func Get(url string) *Response {
res, err := http.Get(url)
if err != nil {
return &Response{}
}
// res.Body != nil when err == nil
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Fatalf("ReadAll: %v", err)
}
reflect.TypeOf(body)
return &Response{sync.Mutex(),string(body), res.StatusCode} // This line is changed.
}

对于 Read() :

func Read(url string, timeout time.Duration) (res *Response) { 
done := make(chan bool)
res = &Response{sync.Mutex()} // this line has been added

go func() {
res = Get(url)
done <- true
}()
select {
case <-done:
case <-time.After(timeout):
res.mu.Lock()
res = &Response{sync.Mutex(), "Gateway timeout\n", 504} // And mutex was added here.

}
defer res.mu.Unlock()
return
}

这个“解决方案”产生了这些错误:

./client.go:54: missing argument to conversion to sync.Mutex: sync.Mutex()
./client.go:63: missing argument to conversion to sync.Mutex: sync.Mutex()
./client.go:63: too few values in struct initializer
./client.go:73: missing argument to conversion to sync.Mutex: sync.Mutex()
./client.go:95: cannot use "Service unavailable\n" (type string) as type sync.Mutex in field value
./client.go:95: cannot use 503 (type int) as type string in field value
./client.go:95: too few values in struct initializer

在这种情况下使用 Mutex 的正确方法是什么?

最佳答案

虽然您对 Volker 指导的回答很好,但您可能需要考虑使用非默认的 http.Client,以便您可以在客户端上设置 Timeout请求(这样您就不必担心自己处理超时)。

关于rest - 如何使用 Mutex 字段创建结构的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36738688/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com