我现在在使用 Gorm 从数据库(Postgres)获取数组提要的 id 时遇到问题。
如何查询并返回 id 数组 feed?我不知道如何在没有循环的情况下从结构中仅获取 id
feeds := []models.Feed{}
feedID := []string{}
db.Select("id").Where("user_id = ?", "admin1").Find(&feeds)
for _, feed := range feeds {
feedID = append(feedID, feed.ID)
}
utils.PrintStruct(feeds)
Run Code Online (Sandbox Code Playgroud)
这是 feed 模型文件:
type Feed struct {
Model
Status string `json:"status"`
PublishAt *time.Time `json:"publishAt"`
UserID string `json:"userID,omitempty"`
}
Run Code Online (Sandbox Code Playgroud)
这是用于数据实体的模型基础数据模型:
type Model struct {
ID string `json:"id" gorm:"primary_key"`
}
Run Code Online (Sandbox Code Playgroud)
结果:
[
{
"id": "d95d4be5-b53c-4c70-aa09",
"status": "",
"publishAt": null,
"userID":""
},
{
"id": "84b2d46f-a24d-4854-b44d",
"status": "",
"publishAt": null,
"userID":"" …Run Code Online (Sandbox Code Playgroud) 我在docker中部署了DgraphAlpha和DgraphZero。我正在按照文档中的描述连接到 Dgraph。
func newClient() *dgo.Dgraph {
d, err := grpc.Dial("localhost:9080", grpc.WithInsecure())
if err != nil {
log.Fatal(err)
}
return dgo.NewDgraphClient(
api.NewDgraphClient(d),
)
}
Run Code Online (Sandbox Code Playgroud)
并且客户端已成功创建,但是当我尝试搜索时
txn := i.dgraphClient.NewReadOnlyTxn()
defer txn.Discard(context.Background())
dgraphQuery := "search here"
response, err := txn.Query(context.Background(), dgraphQuery)
if err != nil {
// error here
}
Run Code Online (Sandbox Code Playgroud)
我收到错误:
rpc error: code = Unavailable desc = connection closed before server preface received
Run Code Online (Sandbox Code Playgroud)
这个错误并不总是在意想不到的时刻发生,因此我很难确定其根源。有人遇到过类似的事情吗?可能是什么问题呢?
在golang中,我通常可以结合使用context.WithTimeout()来exec.CommandContext()获得超时后自动被杀死的命令(使用SIGKILL)。
但我遇到了一个奇怪的问题,如果我通过设置sh -c AND缓冲命令的输出来包装命令cmd.Stdout = &bytes.Buffer{},超时将不再起作用,并且命令将永远运行。
为什么会出现这种情况?
这是一个最小的可重现示例:
package main
import (
"bytes"
"context"
"os/exec"
"time"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
cmdArgs := []string{"sh", "-c", "sleep infinity"}
bufferOutputs := true
// Uncommenting *either* of the next two lines will make the issue go away:
// cmdArgs = []string{"sleep", "infinity"}
// bufferOutputs = false
cmd := exec.CommandContext(ctx, cmdArgs[0], cmdArgs[1:]...)
if bufferOutputs {
cmd.Stdout = &bytes.Buffer{}
}
_ …Run Code Online (Sandbox Code Playgroud) 我正在 Golang 中创建一个 CLI 工具,而且我对 Golang 和为终端制作工具都是新手。我需要直接从我的程序执行终端命令(特别是cd)。我该怎么做呢?我按照这篇文章进行操作,但它抛出一个错误,指出在 %path% 中未找到 echo
预先感谢您的任何帮助!
Go 不支持 try-catch,相反,Go 错误处理的编码风格是在潜在的有效值旁边返回错误。如果错误符合,则错误将被设置为error接口的实现,否则将被设置为nil。
请参阅流动的签名:
func Open(name string) (file *File, err error)
Run Code Online (Sandbox Code Playgroud)
我想知道这个“错误处理”模式的名称是什么。
考虑一组检查工作,每个检查工作都有独立的逻辑,因此它们似乎很适合并发运行,例如:
type Work struct {
// ...
}
// This Check could be quite time-consuming
func (w *Work) Check() bool {
// return succeed or not
//...
}
func CheckAll(works []*Work) {
num := len(works)
results := make(chan bool, num)
for _, w := range works {
go func(w *Work) {
results <- w.Check()
}(w)
}
for i := 0; i < num; i++ {
if r := <-results; !r {
ReportFailed()
break;
}
}
}
func ReportFailed() {
// …Run Code Online (Sandbox Code Playgroud) 我正在尝试将项目的 golang 版本从 升级1.15到1.18.1. 我更改了版本go.mod并执行了go mod tidy命令。
奇怪的是,我的主文件中出现以下错误,该文件main本身有一个函数:
'main' collides with name declared in this package
Run Code Online (Sandbox Code Playgroud)
它发生在net/http和syscall库中:
网络/http
Found several packages [http, main] in '/usr/local/go-1.18.1/src/net/http;/usr/local/go-1.18.1/src/net/http'
Run Code Online (Sandbox Code Playgroud)
系统调用
Found several packages [syscall, main] in '/usr/local/go-1.18.1/src/syscall;/usr/local/go-1.18.1/src/syscall'
Run Code Online (Sandbox Code Playgroud)
当我检查警告是否正确并且两个库中都有主包时。
我应该使用替代库还是应该更改导入它们的方式?
编辑1:
这是一个 IDE 错误,我使用 Goland。
我有这个游乐场:https://go.dev/play/p/uEpYEWaQaV0 但不明白问题是什么以及为什么它不起作用!我收到错误:
invalid character entity &ccb
Run Code Online (Sandbox Code Playgroud)
我的代码是:
package main
import (
"encoding/xml"
"fmt"
)
type catalog struct {
Id string `xml:"id"`
}
type price struct {
Subtotal int `xml:"subtotal"`
Currency string `xml:"currency"`
Total int `xml:"total"`
PriceStatus string `xml:"price_status"`
}
type image struct {
Url string `xml:"url"`
Id int `xml:"id"`
}
type product struct {
Id int `xml:"id"`
RetailerId int `xml:"retailer_id"`
Image image `xml:"image"`
Price int `xml:"price"`
Currency string `xml:"currency"`
Name string `xml:"name"`
Quantity int `xml:"quantity"`
}
type order struct …Run Code Online (Sandbox Code Playgroud) 我在 golang 中使用 jsonpath 但无法获取 iPhone 类型中包含的以下 json 的所有对象:
{
"firstName": "John",
"lastName": "doe",
"age": 26,
"address": {
"streetAddress": "naist street",
"city": "Nara",
"postalCode": "630-0192"
},
"phoneNumbers": [
{
"type": "iPhone",
"number": "0123-4567-8888"
},
{
"type": "home",
"number": "0123-4567-8910"
},
{
"type": "iPhone",
"number": "0123-4567-8910"
}
]}
Run Code Online (Sandbox Code Playgroud)
我正在使用 golang,我知道以下 jsonpath 可以工作:
$.phoneNumbers[?(@.type == "iPhone")]
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是,它是一个服务,我在其中输入了如下所示的 json 路径:
$.[*].phoneNumbers[*].type
Run Code Online (Sandbox Code Playgroud)
我必须寻找的价值是通过以下方式实现的:
values, err := jsonpath.Get(jsonPath, data)
for _, value := range values {
if err != nil {
continue
}
if value.(string) …Run Code Online (Sandbox Code Playgroud)