小编Dav*_*phy的帖子

将项目添加到Go AST后,注释无序

以下测试尝试使用AST将字段添加到结构中.这些字段已正确添加,但注释是按顺序添加的.我收集的位置可能需要手动指定,但我到目前为止找到了一个空白的答案.

这是一个失败的测试:http://play.golang.org/p/RID4N30FZK

这是代码:

package generator

import (
    "bytes"
    "fmt"
    "go/ast"
    "go/parser"
    "go/printer"
    "go/token"
    "testing"
)

func TestAst(t *testing.T) {

    source := `package a

// B comment
type B struct {
    // C comment
    C string
}`

    fset := token.NewFileSet()
    file, err := parser.ParseFile(fset, "", []byte(source), parser.ParseComments)
    if err != nil {
        t.Error(err)
    }

    v := &visitor{
        file: file,
    }
    ast.Walk(v, file)

    var output []byte
    buf := bytes.NewBuffer(output)
    if err := printer.Fprint(buf, fset, file); err != nil { …
Run Code Online (Sandbox Code Playgroud)

abstract-syntax-tree go

22
推荐指数
2
解决办法
896
查看次数

当嵌入类型具有UnmarshalJSON时,json.Unmarshal失败

我正在尝试解组具有嵌入类型的结构.当嵌入类型具有UnmarshalJSON方法时,外部类型的解组失败:

https://play.golang.org/p/Y_Tt5O8A1Q

package main


import (
    "fmt"

    "encoding/json"
)

type Foo struct {
    EmbeddedStruct
    Field string
}

func (d *Foo) UnmarshalJSON(from []byte) error {
    fmt.Printf("Foo.UnmarshalJSON\n")

    type Alias Foo
    alias := &Alias{}
    if err := json.Unmarshal(from, alias); err != nil {
        return fmt.Errorf("Error in Foo.UnmarshalJSON: json.Unmarshal returned an error:\n%v\n", err)
    }
    *d = Foo(*alias)

    return nil
}

type EmbeddedStruct struct {
    EmbeddedField string
}

func (d *EmbeddedStruct) UnmarshalJSON(from []byte) error {
    fmt.Printf("EmbeddedStruct.UnmarshalJSON\n")

    type Alias EmbeddedStruct
    alias := &Alias{}
    if err := …
Run Code Online (Sandbox Code Playgroud)

json go unmarshalling

4
推荐指数
1
解决办法
392
查看次数

防止 ^C 在 Go 中显示在 Ctrl+C 上

我想防止在按下 Ctrl+C 时将“^C”输出到终端。

我正在捕获这样的中断命令:

c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
signal.Notify(c, syscall.SIGTERM)
go func() {
    <-c
    // exit code here
}()
Run Code Online (Sandbox Code Playgroud)

...但是,当我按 Ctrl+C 时,“^C”会输出到终端中。这并不理想。

go

3
推荐指数
1
解决办法
651
查看次数

如何在查询中使用 Firestore DocumentID __name__

我计划使用“in”查询选择器根据 ID 列表返回多个文档。不过,在此示例中我简化为使用“==”:

collection := server.Firestore.Collection("foo")

// Add a document:

ref, _, err := collection.Add(ctx, map[string]string{"a": "b"})
if err != nil {
    panic(err)
}

// Here's the document ID:

fmt.Println("ref.ID", ref.ID)

// Get all the documents in the collection just to check it's there:

allDocs, err := collection.Query.Documents(ctx).GetAll()
if err != nil {
    panic(err)
}
fmt.Println("len(allDocs):", len(allDocs))

// Check our document is the one in the collection:

fmt.Println("allDocs[0].Ref.ID", allDocs[0].Ref.ID)

// Get the document using __name__ query:

docQuery, err := collection.Query.Where(firestore.DocumentID, …
Run Code Online (Sandbox Code Playgroud)

go gcloud google-cloud-firestore

1
推荐指数
1
解决办法
1992
查看次数