Dataset Viewer
Auto-converted to Parquet
element_type
stringclasses
2 values
project_name
stringclasses
2 values
uuid
stringlengths
36
36
name
stringlengths
3
29
imports
stringlengths
0
312
structs
stringclasses
7 values
interfaces
stringclasses
1 value
file_location
stringlengths
49
107
code
stringlengths
41
7.22k
global_vars
stringclasses
3 values
package
stringclasses
11 values
tags
stringclasses
1 value
file
test
4f2feec5-1b7d-4029-b9a5-4ebf4b50d1ba
app.go
import ( "fmt" "net/http" )
github.com/test//tmp/repos/example/appengine-hello/app.go
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package hello is a simple App Engine application that replies to requests // on /hello with a welcoming message. package hello import ( "fmt" "net/http" ) // init is run before the application starts serving. func init() { // Handle all requests with path /hello with the helloHandler function. http.HandleFunc("/hello", helloHandler) } func helloHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello from the Go app") }
package hello
function
test
f85d0e31-cd89-4c15-b213-d3a20539b45b
init
['"net/http"']
github.com/test//tmp/repos/example/appengine-hello/app.go
func init() { // Handle all requests with path /hello with the helloHandler function. http.HandleFunc("/hello", helloHandler) }
hello
function
test
5928dc2d-1804-4445-89f2-baa319640ecd
helloHandler
['"fmt"', '"net/http"']
github.com/test//tmp/repos/example/appengine-hello/app.go
func helloHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello from the Go app") }
hello
file
test
37334d6a-f93f-4763-b7fa-5702a3ff6da1
main.go
import ( "fmt" "go/ast" "go/importer" "go/parser" "go/token" "go/types" "log" )
github.com/test//tmp/repos/example/gotypes/defsuses/main.go
package main import ( "fmt" "go/ast" "go/importer" "go/parser" "go/token" "go/types" "log" ) const hello = `package main import "fmt" func main() { fmt.Println("Hello, world") } ` // !+ func PrintDefsUses(fset *token.FileSet, files ...*ast.File) error { conf := types.Config{Importer: importer.Default()} info := &types.Info{ Defs: make(map[*ast.Ident]types.Object), Uses: make(map[*ast.Ident]types.Object), } _, err := conf.Check("hello", fset, files, info) if err != nil { return err // type error } for id, obj := range info.Defs { fmt.Printf("%s: %q defines %v\n", fset.Position(id.Pos()), id.Name, obj) } for id, obj := range info.Uses { fmt.Printf("%s: %q uses %v\n", fset.Position(id.Pos()), id.Name, obj) } return nil } //!- func main() { // Parse one file. fset := token.NewFileSet() f, err := parser.ParseFile(fset, "hello.go", hello, 0) if err != nil { log.Fatal(err) // parse error } if err := PrintDefsUses(fset, f); err != nil { log.Fatal(err) // type error } } /* //!+output $ go build golang.org/x/example/gotypes/defsuses $ ./defsuses hello.go:1:9: "main" defines <nil> hello.go:5:6: "main" defines func hello.main() hello.go:6:9: "fmt" uses package fmt hello.go:6:13: "Println" uses func fmt.Println(a ...interface{}) (n int, err error) //!-output */
package main
function
test
9fee1c32-7bbc-4bc1-a46c-e1d99b4291da
PrintDefsUses
['"fmt"', '"go/ast"', '"go/importer"', '"go/token"', '"go/types"']
github.com/test//tmp/repos/example/gotypes/defsuses/main.go
func PrintDefsUses(fset *token.FileSet, files ...*ast.File) error { conf := types.Config{Importer: importer.Default()} info := &types.Info{ Defs: make(map[*ast.Ident]types.Object), Uses: make(map[*ast.Ident]types.Object), } _, err := conf.Check("hello", fset, files, info) if err != nil { return err // type error } for id, obj := range info.Defs { fmt.Printf("%s: %q defines %v\n", fset.Position(id.Pos()), id.Name, obj) } for id, obj := range info.Uses { fmt.Printf("%s: %q uses %v\n", fset.Position(id.Pos()), id.Name, obj) } return nil }
main
function
test
9d1f20f6-80ea-483e-85e1-23065b9693ef
main
['"go/parser"', '"go/token"', '"log"']
github.com/test//tmp/repos/example/gotypes/defsuses/main.go
func main() { // Parse one file. fset := token.NewFileSet() f, err := parser.ParseFile(fset, "hello.go", hello, 0) if err != nil { log.Fatal(err) // parse error } if err := PrintDefsUses(fset, f); err != nil { log.Fatal(err) // type error } }
main
file
test
8b84126e-0791-4ee4-b7ab-4a1bf3e0ca49
main.go
import ( "fmt" "go/ast" "log" "os" "golang.org/x/tools/go/ast/astutil" "golang.org/x/tools/go/packages" "golang.org/x/tools/go/types/typeutil" )
github.com/test//tmp/repos/example/gotypes/doc/main.go
// The doc command prints the doc comment of a package-level object. package main import ( "fmt" "go/ast" "log" "os" "golang.org/x/tools/go/ast/astutil" "golang.org/x/tools/go/packages" "golang.org/x/tools/go/types/typeutil" ) func main() { if len(os.Args) != 3 { log.Fatal("Usage: doc <package> <object>") } //!+part1 pkgpath, name := os.Args[1], os.Args[2] // Load complete type information for the specified packages, // along with type-annotated syntax. // Types for dependencies are loaded from export data. conf := &packages.Config{Mode: packages.LoadSyntax} pkgs, err := packages.Load(conf, pkgpath) if err != nil { log.Fatal(err) // failed to load anything } if packages.PrintErrors(pkgs) > 0 { os.Exit(1) // some packages contained errors } // Find the package and package-level object. pkg := pkgs[0] obj := pkg.Types.Scope().Lookup(name) if obj == nil { log.Fatalf("%s.%s not found", pkg.Types.Path(), name) } //!-part1 //!+part2 // Print the object and its methods (incl. location of definition). fmt.Println(obj) for _, sel := range typeutil.IntuitiveMethodSet(obj.Type(), nil) { fmt.Printf("%s: %s\n", pkg.Fset.Position(sel.Obj().Pos()), sel) } // Find the path from the root of the AST to the object's position. // Walk up to the enclosing ast.Decl for the doc comment. for _, file := range pkg.Syntax { pos := obj.Pos() if !(file.FileStart <= pos && pos < file.FileEnd) { continue // not in this file } path, _ := astutil.PathEnclosingInterval(file, pos, pos) for _, n := range path { switch n := n.(type) { case *ast.GenDecl: fmt.Println("\n", n.Doc.Text()) return case *ast.FuncDecl: fmt.Println("\n", n.Doc.Text()) return } } } //!-part2 } // (The $GOROOT below is the actual string that appears in file names // loaded from export data for packages in the standard library.) /* //!+output $ ./doc net/http File type net/http.File interface{Readdir(count int) ([]os.FileInfo, error); Seek(offset int64, whence int) (int64, error); Stat() (os.FileInfo, error); io.Closer; io.Reader} $GOROOT/src/io/io.go:92:2: method (net/http.File) Close() error $GOROOT/src/io/io.go:71:2: method (net/http.File) Read(p []byte) (n int, err error) /go/src/net/http/fs.go:65:2: method (net/http.File) Readdir(count int) ([]os.FileInfo, error) $GOROOT/src/net/http/fs.go:66:2: method (net/http.File) Seek(offset int64, whence int) (int64, error) /go/src/net/http/fs.go:67:2: method (net/http.File) Stat() (os.FileInfo, error) A File is returned by a FileSystem's Open method and can be served by the FileServer implementation. The methods should behave the same as those on an *os.File. //!-output */
package main
function
test
0de5bc5d-5f1b-4f7e-a392-773602f8536c
main
['"fmt"', '"go/ast"', '"log"', '"os"', '"golang.org/x/tools/go/ast/astutil"', '"golang.org/x/tools/go/packages"', '"golang.org/x/tools/go/types/typeutil"']
github.com/test//tmp/repos/example/gotypes/doc/main.go
func main() { if len(os.Args) != 3 { log.Fatal("Usage: doc <package> <object>") } //!+part1 pkgpath, name := os.Args[1], os.Args[2] // Load complete type information for the specified packages, // along with type-annotated syntax. // Types for dependencies are loaded from export data. conf := &packages.Config{Mode: packages.LoadSyntax} pkgs, err := packages.Load(conf, pkgpath) if err != nil { log.Fatal(err) // failed to load anything } if packages.PrintErrors(pkgs) > 0 { os.Exit(1) // some packages contained errors } // Find the package and package-level object. pkg := pkgs[0] obj := pkg.Types.Scope().Lookup(name) if obj == nil { log.Fatalf("%s.%s not found", pkg.Types.Path(), name) } //!-part1 //!+part2 // Print the object and its methods (incl. location of definition). fmt.Println(obj) for _, sel := range typeutil.IntuitiveMethodSet(obj.Type(), nil) { fmt.Printf("%s: %s\n", pkg.Fset.Position(sel.Obj().Pos()), sel) } // Find the path from the root of the AST to the object's position. // Walk up to the enclosing ast.Decl for the doc comment. for _, file := range pkg.Syntax { pos := obj.Pos() if !(file.FileStart <= pos && pos < file.FileEnd) { continue // not in this file } path, _ := astutil.PathEnclosingInterval(file, pos, pos) for _, n := range path { switch n := n.(type) { case *ast.GenDecl: fmt.Println("\n", n.Doc.Text()) return case *ast.FuncDecl: fmt.Println("\n", n.Doc.Text()) return } } } //!-part2 }
main
file
test
2d76e11a-a74f-4990-aeb9-8d3d90487248
gen.go
github.com/test//tmp/repos/example/gotypes/gen.go
//go:generate bash -c "go run ../internal/cmd/weave/weave.go ./go-types.md > README.md" package gotypes
package gotypes
file
test
a506e787-b209-4f9b-b310-09fc8e7644c6
hello.go
import "fmt"
github.com/test//tmp/repos/example/gotypes/hello/hello.go
// !+ package main import "fmt" func main() { fmt.Println("Hello, 世界") } //!-
package main
function
test
74a8e46a-da20-44f2-be7f-f20065f23360
main
github.com/test//tmp/repos/example/gotypes/hello/hello.go
func main() { fmt.Println("Hello, 世界") }
main
file
test
aa43a7ef-9f3e-40b5-b829-83477bc15fb0
main.go
import ( "flag" "fmt" "go/ast" "go/token" "go/types" "log" "os" "golang.org/x/tools/go/packages" )
github.com/test//tmp/repos/example/gotypes/hugeparam/main.go
// The hugeparam command identifies by-value parameters that are larger than n bytes. // // Example: // // $ ./hugeparams encoding/xml package main import ( "flag" "fmt" "go/ast" "go/token" "go/types" "log" "os" "golang.org/x/tools/go/packages" ) // !+ var bytesFlag = flag.Int("bytes", 48, "maximum parameter size in bytes") func PrintHugeParams(fset *token.FileSet, info *types.Info, sizes types.Sizes, files []*ast.File) { checkTuple := func(descr string, tuple *types.Tuple) { for i := 0; i < tuple.Len(); i++ { v := tuple.At(i) if sz := sizes.Sizeof(v.Type()); sz > int64(*bytesFlag) { fmt.Printf("%s: %q %s: %s = %d bytes\n", fset.Position(v.Pos()), v.Name(), descr, v.Type(), sz) } } } checkSig := func(sig *types.Signature) { checkTuple("parameter", sig.Params()) checkTuple("result", sig.Results()) } for _, file := range files { ast.Inspect(file, func(n ast.Node) bool { switch n := n.(type) { case *ast.FuncDecl: checkSig(info.Defs[n.Name].Type().(*types.Signature)) case *ast.FuncLit: checkSig(info.Types[n.Type].Type.(*types.Signature)) } return true }) } } //!- func main() { flag.Parse() // Load complete type information for the specified packages, // along with type-annotated syntax and the "sizeof" function. // Types for dependencies are loaded from export data. conf := &packages.Config{Mode: packages.LoadSyntax} pkgs, err := packages.Load(conf, flag.Args()...) if err != nil { log.Fatal(err) // failed to load anything } if packages.PrintErrors(pkgs) > 0 { os.Exit(1) // some packages contained errors } for _, pkg := range pkgs { PrintHugeParams(pkg.Fset, pkg.TypesInfo, pkg.TypesSizes, pkg.Syntax) } } /* //!+output % ./hugeparam encoding/xml /go/src/encoding/xml/marshal.go:167:50: "start" parameter: encoding/xml.StartElement = 56 bytes /go/src/encoding/xml/marshal.go:734:97: "" result: encoding/xml.StartElement = 56 bytes /go/src/encoding/xml/marshal.go:761:51: "start" parameter: encoding/xml.StartElement = 56 bytes /go/src/encoding/xml/marshal.go:781:68: "start" parameter: encoding/xml.StartElement = 56 bytes /go/src/encoding/xml/xml.go:72:30: "" result: encoding/xml.StartElement = 56 bytes //!-output */
package main
function
test
5b0c851f-2a72-431b-94c5-597a3e65ce1a
PrintHugeParams
['"fmt"', '"go/ast"', '"go/token"', '"go/types"']
github.com/test//tmp/repos/example/gotypes/hugeparam/main.go
func PrintHugeParams(fset *token.FileSet, info *types.Info, sizes types.Sizes, files []*ast.File) { checkTuple := func(descr string, tuple *types.Tuple) { for i := 0; i < tuple.Len(); i++ { v := tuple.At(i) if sz := sizes.Sizeof(v.Type()); sz > int64(*bytesFlag) { fmt.Printf("%s: %q %s: %s = %d bytes\n", fset.Position(v.Pos()), v.Name(), descr, v.Type(), sz) } } } checkSig := func(sig *types.Signature) { checkTuple("parameter", sig.Params()) checkTuple("result", sig.Results()) } for _, file := range files { ast.Inspect(file, func(n ast.Node) bool { switch n := n.(type) { case *ast.FuncDecl: checkSig(info.Defs[n.Name].Type().(*types.Signature)) case *ast.FuncLit: checkSig(info.Types[n.Type].Type.(*types.Signature)) } return true }) } }
{'bytesFlag': 'flag.Int("bytes", 48, "maximum parameter size in bytes")'}
main
function
test
d7e80d1a-0826-429b-980a-589c640e3e02
main
['"flag"', '"log"', '"os"', '"golang.org/x/tools/go/packages"']
github.com/test//tmp/repos/example/gotypes/hugeparam/main.go
func main() { flag.Parse() // Load complete type information for the specified packages, // along with type-annotated syntax and the "sizeof" function. // Types for dependencies are loaded from export data. conf := &packages.Config{Mode: packages.LoadSyntax} pkgs, err := packages.Load(conf, flag.Args()...) if err != nil { log.Fatal(err) // failed to load anything } if packages.PrintErrors(pkgs) > 0 { os.Exit(1) // some packages contained errors } for _, pkg := range pkgs { PrintHugeParams(pkg.Fset, pkg.TypesInfo, pkg.TypesSizes, pkg.Syntax) } }
main
file
test
913cdeed-5781-4e26-9da7-fd7ba6566489
main.go
import ( "fmt" "go/ast" "go/importer" "go/parser" "go/token" "go/types" "log" )
github.com/test//tmp/repos/example/gotypes/implements/main.go
package main import ( "fmt" "go/ast" "go/importer" "go/parser" "go/token" "go/types" "log" ) // !+input const input = `package main type A struct{} func (*A) f() type B int func (B) f() func (*B) g() type I interface { f() } type J interface { g() } ` //!-input func main() { // Parse one file. fset := token.NewFileSet() f, err := parser.ParseFile(fset, "input.go", input, 0) if err != nil { log.Fatal(err) // parse error } conf := types.Config{Importer: importer.Default()} pkg, err := conf.Check("hello", fset, []*ast.File{f}, nil) if err != nil { log.Fatal(err) // type error } //!+implements // Find all named types at package level. var allNamed []*types.Named for _, name := range pkg.Scope().Names() { if obj, ok := pkg.Scope().Lookup(name).(*types.TypeName); ok { allNamed = append(allNamed, obj.Type().(*types.Named)) } } // Test assignability of all distinct pairs of // named types (T, U) where U is an interface. for _, T := range allNamed { for _, U := range allNamed { if T == U || !types.IsInterface(U) { continue } if types.AssignableTo(T, U) { fmt.Printf("%s satisfies %s\n", T, U) } else if !types.IsInterface(T) && types.AssignableTo(types.NewPointer(T), U) { fmt.Printf("%s satisfies %s\n", types.NewPointer(T), U) } } } //!-implements } /* //!+output $ go build golang.org/x/example/gotypes/implements $ ./implements *hello.A satisfies hello.I hello.B satisfies hello.I *hello.B satisfies hello.J //!-output */
package main
function
test
e0c89923-e90d-4c1e-aaac-2b013abd9a15
main
['"fmt"', '"go/ast"', '"go/importer"', '"go/parser"', '"go/token"', '"go/types"', '"log"']
github.com/test//tmp/repos/example/gotypes/implements/main.go
func main() { // Parse one file. fset := token.NewFileSet() f, err := parser.ParseFile(fset, "input.go", input, 0) if err != nil { log.Fatal(err) // parse error } conf := types.Config{Importer: importer.Default()} pkg, err := conf.Check("hello", fset, []*ast.File{f}, nil) if err != nil { log.Fatal(err) // type error } //!+implements // Find all named types at package level. var allNamed []*types.Named for _, name := range pkg.Scope().Names() { if obj, ok := pkg.Scope().Lookup(name).(*types.TypeName); ok { allNamed = append(allNamed, obj.Type().(*types.Named)) } } // Test assignability of all distinct pairs of // named types (T, U) where U is an interface. for _, T := range allNamed { for _, U := range allNamed { if T == U || !types.IsInterface(U) { continue } if types.AssignableTo(T, U) { fmt.Printf("%s satisfies %s\n", T, U) } else if !types.IsInterface(T) && types.AssignableTo(types.NewPointer(T), U) { fmt.Printf("%s satisfies %s\n", types.NewPointer(T), U) } } } //!-implements }
main
file
test
fc27821d-0d14-48ec-8fe6-3ccc90aeb26b
lookup.go
import ( "fmt" "go/ast" "go/importer" "go/parser" "go/token" "go/types" "log" "strings" )
github.com/test//tmp/repos/example/gotypes/lookup/lookup.go
package main import ( "fmt" "go/ast" "go/importer" "go/parser" "go/token" "go/types" "log" "strings" ) // !+input const hello = ` package main import "fmt" // append func main() { // fmt fmt.Println("Hello, world") // main main, x := 1, 2 // main print(main, x) // x } // x ` //!-input // !+main func main() { fset := token.NewFileSet() f, err := parser.ParseFile(fset, "hello.go", hello, parser.ParseComments) if err != nil { log.Fatal(err) // parse error } conf := types.Config{Importer: importer.Default()} pkg, err := conf.Check("cmd/hello", fset, []*ast.File{f}, nil) if err != nil { log.Fatal(err) // type error } // Each comment contains a name. // Look up that name in the innermost scope enclosing the comment. for _, comment := range f.Comments { pos := comment.Pos() name := strings.TrimSpace(comment.Text()) fmt.Printf("At %s,\t%q = ", fset.Position(pos), name) inner := pkg.Scope().Innermost(pos) if _, obj := inner.LookupParent(name, pos); obj != nil { fmt.Println(obj) } else { fmt.Println("not found") } } } //!-main /* //!+output $ go build golang.org/x/example/gotypes/lookup $ ./lookup At hello.go:6:1, "append" = builtin append At hello.go:8:9, "fmt" = package fmt At hello.go:10:9, "main" = func cmd/hello.main() At hello.go:12:9, "main" = var main int At hello.go:14:9, "x" = var x int At hello.go:16:1, "x" = not found //!-output */
package main
function
test
806dd6aa-9670-4860-82e8-3f6356e80b50
main
['"fmt"', '"go/ast"', '"go/importer"', '"go/parser"', '"go/token"', '"go/types"', '"log"', '"strings"']
github.com/test//tmp/repos/example/gotypes/lookup/lookup.go
func main() { fset := token.NewFileSet() f, err := parser.ParseFile(fset, "hello.go", hello, parser.ParseComments) if err != nil { log.Fatal(err) // parse error } conf := types.Config{Importer: importer.Default()} pkg, err := conf.Check("cmd/hello", fset, []*ast.File{f}, nil) if err != nil { log.Fatal(err) // type error } // Each comment contains a name. // Look up that name in the innermost scope enclosing the comment. for _, comment := range f.Comments { pos := comment.Pos() name := strings.TrimSpace(comment.Text()) fmt.Printf("At %s,\t%q = ", fset.Position(pos), name) inner := pkg.Scope().Innermost(pos) if _, obj := inner.LookupParent(name, pos); obj != nil { fmt.Println(obj) } else { fmt.Println("not found") } } }
main
file
test
9dd0d73d-f5dc-43a1-a3b8-4824a5d9f0a5
main.go
import ( "fmt" "go/ast" "go/importer" "go/parser" "go/token" "go/types" "log" )
github.com/test//tmp/repos/example/gotypes/nilfunc/main.go
package main import ( "fmt" "go/ast" "go/importer" "go/parser" "go/token" "go/types" "log" ) // !+input const input = `package main import "bytes" func main() { var buf bytes.Buffer if buf.Bytes == nil && bytes.Repeat != nil && main == nil { // ... } } ` //!-input var fset = token.NewFileSet() func main() { f, err := parser.ParseFile(fset, "input.go", input, 0) if err != nil { log.Fatal(err) // parse error } conf := types.Config{Importer: importer.Default()} info := &types.Info{ Defs: make(map[*ast.Ident]types.Object), Uses: make(map[*ast.Ident]types.Object), Types: make(map[ast.Expr]types.TypeAndValue), } if _, err = conf.Check("cmd/hello", fset, []*ast.File{f}, info); err != nil { log.Fatal(err) // type error } ast.Inspect(f, func(n ast.Node) bool { if n != nil { CheckNilFuncComparison(info, n) } return true }) } // !+ // CheckNilFuncComparison reports unintended comparisons // of functions against nil, e.g., "if x.Method == nil {". func CheckNilFuncComparison(info *types.Info, n ast.Node) { e, ok := n.(*ast.BinaryExpr) if !ok { return // not a binary operation } if e.Op != token.EQL && e.Op != token.NEQ { return // not a comparison } // If this is a comparison against nil, find the other operand. var other ast.Expr if info.Types[e.X].IsNil() { other = e.Y } else if info.Types[e.Y].IsNil() { other = e.X } else { return // not a comparison against nil } // Find the object. var obj types.Object switch v := other.(type) { case *ast.Ident: obj = info.Uses[v] case *ast.SelectorExpr: obj = info.Uses[v.Sel] default: return // not an identifier or selection } if _, ok := obj.(*types.Func); !ok { return // not a function or method } fmt.Printf("%s: comparison of function %v %v nil is always %v\n", fset.Position(e.Pos()), obj.Name(), e.Op, e.Op == token.NEQ) } //!- /* //!+output $ go build golang.org/x/example/gotypes/nilfunc $ ./nilfunc input.go:7:5: comparison of function Bytes == nil is always false input.go:7:25: comparison of function Repeat != nil is always true input.go:7:48: comparison of function main == nil is always false //!-output */
package main
function
test
92f49bb1-698b-4e3c-9dc1-3c8eabab4e21
main
['"go/ast"', '"go/importer"', '"go/parser"', '"go/types"', '"log"']
github.com/test//tmp/repos/example/gotypes/nilfunc/main.go
func main() { f, err := parser.ParseFile(fset, "input.go", input, 0) if err != nil { log.Fatal(err) // parse error } conf := types.Config{Importer: importer.Default()} info := &types.Info{ Defs: make(map[*ast.Ident]types.Object), Uses: make(map[*ast.Ident]types.Object), Types: make(map[ast.Expr]types.TypeAndValue), } if _, err = conf.Check("cmd/hello", fset, []*ast.File{f}, info); err != nil { log.Fatal(err) // type error } ast.Inspect(f, func(n ast.Node) bool { if n != nil { CheckNilFuncComparison(info, n) } return true }) }
{'fset': 'token.NewFileSet()'}
main
function
test
a82fb36d-15ac-4842-8121-d4417327a4cf
CheckNilFuncComparison
['"fmt"', '"go/ast"', '"go/token"', '"go/types"']
github.com/test//tmp/repos/example/gotypes/nilfunc/main.go
func CheckNilFuncComparison(info *types.Info, n ast.Node) { e, ok := n.(*ast.BinaryExpr) if !ok { return // not a binary operation } if e.Op != token.EQL && e.Op != token.NEQ { return // not a comparison } // If this is a comparison against nil, find the other operand. var other ast.Expr if info.Types[e.X].IsNil() { other = e.Y } else if info.Types[e.Y].IsNil() { other = e.X } else { return // not a comparison against nil } // Find the object. var obj types.Object switch v := other.(type) { case *ast.Ident: obj = info.Uses[v] case *ast.SelectorExpr: obj = info.Uses[v.Sel] default: return // not an identifier or selection } if _, ok := obj.(*types.Func); !ok { return // not a function or method } fmt.Printf("%s: comparison of function %v %v nil is always %v\n", fset.Position(e.Pos()), obj.Name(), e.Op, e.Op == token.NEQ) }
{'fset': 'token.NewFileSet()'}
main
file
test
2c2dd520-8ed3-429f-9a98-863428489c05
main.go
import ( "fmt" "go/ast" "go/importer" "go/parser" "go/token" "go/types" "log" )
github.com/test//tmp/repos/example/gotypes/pkginfo/main.go
// !+ package main import ( "fmt" "go/ast" "go/importer" "go/parser" "go/token" "go/types" "log" ) const hello = `package main import "fmt" func main() { fmt.Println("Hello, world") }` func main() { fset := token.NewFileSet() // Parse the input string, []byte, or io.Reader, // recording position information in fset. // ParseFile returns an *ast.File, a syntax tree. f, err := parser.ParseFile(fset, "hello.go", hello, 0) if err != nil { log.Fatal(err) // parse error } // A Config controls various options of the type checker. // The defaults work fine except for one setting: // we must specify how to deal with imports. conf := types.Config{Importer: importer.Default()} // Type-check the package containing only file f. // Check returns a *types.Package. pkg, err := conf.Check("cmd/hello", fset, []*ast.File{f}, nil) if err != nil { log.Fatal(err) // type error } fmt.Printf("Package %q\n", pkg.Path()) fmt.Printf("Name: %s\n", pkg.Name()) fmt.Printf("Imports: %s\n", pkg.Imports()) fmt.Printf("Scope: %s\n", pkg.Scope()) } //!- /* //!+output $ go build golang.org/x/example/gotypes/pkginfo $ ./pkginfo Package "cmd/hello" Name: main Imports: [package fmt ("fmt")] Scope: package "cmd/hello" scope 0x820533590 { . func cmd/hello.main() } //!-output */
package main
function
test
9635a82e-95fa-4d20-86ee-7b950e2db966
main
['"fmt"', '"go/ast"', '"go/importer"', '"go/parser"', '"go/token"', '"go/types"', '"log"']
github.com/test//tmp/repos/example/gotypes/pkginfo/main.go
func main() { fset := token.NewFileSet() // Parse the input string, []byte, or io.Reader, // recording position information in fset. // ParseFile returns an *ast.File, a syntax tree. f, err := parser.ParseFile(fset, "hello.go", hello, 0) if err != nil { log.Fatal(err) // parse error } // A Config controls various options of the type checker. // The defaults work fine except for one setting: // we must specify how to deal with imports. conf := types.Config{Importer: importer.Default()} // Type-check the package containing only file f. // Check returns a *types.Package. pkg, err := conf.Check("cmd/hello", fset, []*ast.File{f}, nil) if err != nil { log.Fatal(err) // type error } fmt.Printf("Package %q\n", pkg.Path()) fmt.Printf("Name: %s\n", pkg.Name()) fmt.Printf("Imports: %s\n", pkg.Imports()) fmt.Printf("Scope: %s\n", pkg.Scope()) }
main
file
test
dfe43f0e-2c06-46cc-9746-5f86fd8a95db
main.go
import ( "fmt" "go/types" "log" "os" "strings" "unicode" "unicode/utf8" "golang.org/x/tools/go/packages" )
github.com/test//tmp/repos/example/gotypes/skeleton/main.go
// The skeleton command prints the boilerplate for a concrete type // that implements the specified interface type. // // Example: // // $ ./skeleton io ReadWriteCloser buffer // // *buffer implements io.ReadWriteCloser. // type buffer struct{ /* ... */ } // func (b *buffer) Close() error { panic("unimplemented") } // func (b *buffer) Read(p []byte) (n int, err error) { panic("unimplemented") } // func (b *buffer) Write(p []byte) (n int, err error) { panic("unimplemented") } package main import ( "fmt" "go/types" "log" "os" "strings" "unicode" "unicode/utf8" "golang.org/x/tools/go/packages" ) const usage = "Usage: skeleton <package> <interface> <concrete>" // !+ func PrintSkeleton(pkg *types.Package, ifacename, concname string) error { obj := pkg.Scope().Lookup(ifacename) if obj == nil { return fmt.Errorf("%s.%s not found", pkg.Path(), ifacename) } if _, ok := obj.(*types.TypeName); !ok { return fmt.Errorf("%v is not a named type", obj) } iface, ok := obj.Type().Underlying().(*types.Interface) if !ok { return fmt.Errorf("type %v is a %T, not an interface", obj, obj.Type().Underlying()) } // Use first letter of type name as receiver parameter. if !isValidIdentifier(concname) { return fmt.Errorf("invalid concrete type name: %q", concname) } r, _ := utf8.DecodeRuneInString(concname) fmt.Printf("// *%s implements %s.%s.\n", concname, pkg.Path(), ifacename) fmt.Printf("type %s struct{}\n", concname) mset := types.NewMethodSet(iface) for i := 0; i < mset.Len(); i++ { meth := mset.At(i).Obj() sig := types.TypeString(meth.Type(), (*types.Package).Name) fmt.Printf("func (%c *%s) %s%s {\n\tpanic(\"unimplemented\")\n}\n", r, concname, meth.Name(), strings.TrimPrefix(sig, "func")) } return nil } //!- func isValidIdentifier(id string) bool { for i, r := range id { if !unicode.IsLetter(r) && !(i > 0 && unicode.IsDigit(r)) { return false } } return id != "" } func main() { if len(os.Args) != 4 { log.Fatal(usage) } pkgpath, ifacename, concname := os.Args[1], os.Args[2], os.Args[3] // Load only exported type information for the specified package. conf := &packages.Config{Mode: packages.NeedTypes} pkgs, err := packages.Load(conf, pkgpath) if err != nil { log.Fatal(err) // failed to load anything } if packages.PrintErrors(pkgs) > 0 { os.Exit(1) // some packages contained errors } if err := PrintSkeleton(pkgs[0].Types, ifacename, concname); err != nil { log.Fatal(err) } } /* //!+output1 $ ./skeleton io ReadWriteCloser buffer // *buffer implements io.ReadWriteCloser. type buffer struct{} func (b *buffer) Close() error { panic("unimplemented") } func (b *buffer) Read(p []byte) (n int, err error) { panic("unimplemented") } func (b *buffer) Write(p []byte) (n int, err error) { panic("unimplemented") } //!-output1 //!+output2 $ ./skeleton net/http Handler myHandler // *myHandler implements net/http.Handler. type myHandler struct{} func (m *myHandler) ServeHTTP(http.ResponseWriter, *http.Request) { panic("unimplemented") } //!-output2 */
package main
function
test
a95d7742-da6f-45e4-b9b0-55f07bc5dbc1
PrintSkeleton
['"fmt"', '"go/types"', '"strings"', '"unicode/utf8"']
github.com/test//tmp/repos/example/gotypes/skeleton/main.go
func PrintSkeleton(pkg *types.Package, ifacename, concname string) error { obj := pkg.Scope().Lookup(ifacename) if obj == nil { return fmt.Errorf("%s.%s not found", pkg.Path(), ifacename) } if _, ok := obj.(*types.TypeName); !ok { return fmt.Errorf("%v is not a named type", obj) } iface, ok := obj.Type().Underlying().(*types.Interface) if !ok { return fmt.Errorf("type %v is a %T, not an interface", obj, obj.Type().Underlying()) } // Use first letter of type name as receiver parameter. if !isValidIdentifier(concname) { return fmt.Errorf("invalid concrete type name: %q", concname) } r, _ := utf8.DecodeRuneInString(concname) fmt.Printf("// *%s implements %s.%s.\n", concname, pkg.Path(), ifacename) fmt.Printf("type %s struct{}\n", concname) mset := types.NewMethodSet(iface) for i := 0; i < mset.Len(); i++ { meth := mset.At(i).Obj() sig := types.TypeString(meth.Type(), (*types.Package).Name) fmt.Printf("func (%c *%s) %s%s {\n\tpanic(\"unimplemented\")\n}\n", r, concname, meth.Name(), strings.TrimPrefix(sig, "func")) } return nil }
main
function
test
b94ba54c-bb66-4c06-b36c-8811728577aa
isValidIdentifier
['"unicode"']
github.com/test//tmp/repos/example/gotypes/skeleton/main.go
func isValidIdentifier(id string) bool { for i, r := range id { if !unicode.IsLetter(r) && !(i > 0 && unicode.IsDigit(r)) { return false } } return id != "" }
main
function
test
df0b8b80-efa7-492a-822c-1d97c85938e1
main
['"log"', '"os"', '"golang.org/x/tools/go/packages"']
github.com/test//tmp/repos/example/gotypes/skeleton/main.go
func main() { if len(os.Args) != 4 { log.Fatal(usage) } pkgpath, ifacename, concname := os.Args[1], os.Args[2], os.Args[3] // Load only exported type information for the specified package. conf := &packages.Config{Mode: packages.NeedTypes} pkgs, err := packages.Load(conf, pkgpath) if err != nil { log.Fatal(err) // failed to load anything } if packages.PrintErrors(pkgs) > 0 { os.Exit(1) // some packages contained errors } if err := PrintSkeleton(pkgs[0].Types, ifacename, concname); err != nil { log.Fatal(err) } }
main
file
test
aa907d3b-c64f-4fd8-b1ac-9c543d9837e7
main.go
import ( "bytes" "fmt" "go/ast" "go/format" "go/importer" "go/parser" "go/token" "go/types" "log" )
github.com/test//tmp/repos/example/gotypes/typeandvalue/main.go
package main import ( "bytes" "fmt" "go/ast" "go/format" "go/importer" "go/parser" "go/token" "go/types" "log" ) // !+input const input = ` package main var m = make(map[string]int) func main() { v, ok := m["hello, " + "world"] print(rune(v), ok) } ` //!-input var fset = token.NewFileSet() func main() { f, err := parser.ParseFile(fset, "hello.go", input, 0) if err != nil { log.Fatal(err) // parse error } conf := types.Config{Importer: importer.Default()} info := &types.Info{Types: make(map[ast.Expr]types.TypeAndValue)} if _, err := conf.Check("cmd/hello", fset, []*ast.File{f}, info); err != nil { log.Fatal(err) // type error } //!+inspect // f is a parsed, type-checked *ast.File. ast.Inspect(f, func(n ast.Node) bool { if expr, ok := n.(ast.Expr); ok { if tv, ok := info.Types[expr]; ok { fmt.Printf("%-24s\tmode: %s\n", nodeString(expr), mode(tv)) fmt.Printf("\t\t\t\ttype: %v\n", tv.Type) if tv.Value != nil { fmt.Printf("\t\t\t\tvalue: %v\n", tv.Value) } } } return true }) //!-inspect } // nodeString formats a syntax tree in the style of gofmt. func nodeString(n ast.Node) string { var buf bytes.Buffer format.Node(&buf, fset, n) return buf.String() } // mode returns a string describing the mode of an expression. func mode(tv types.TypeAndValue) string { s := "" if tv.IsVoid() { s += ",void" } if tv.IsType() { s += ",type" } if tv.IsBuiltin() { s += ",builtin" } if tv.IsValue() { s += ",value" } if tv.IsNil() { s += ",nil" } if tv.Addressable() { s += ",addressable" } if tv.Assignable() { s += ",assignable" } if tv.HasOk() { s += ",ok" } return s[1:] } /* //!+output $ go build golang.org/x/example/gotypes/typeandvalue $ ./typeandvalue make(map[string]int) mode: value type: map[string]int make mode: builtin type: func(map[string]int) map[string]int map[string]int mode: type type: map[string]int string mode: type type: string int mode: type type: int m["hello, "+"world"] mode: value,assignable,ok type: (int, bool) m mode: value,addressable,assignable type: map[string]int "hello, " + "world" mode: value type: string value: "hello, world" "hello, " mode: value type: untyped string value: "hello, " "world" mode: value type: untyped string value: "world" print(rune(v), ok) mode: void type: () print mode: builtin type: func(rune, bool) rune(v) mode: value type: rune rune mode: type type: rune ...more not shown... //!-output */
package main
function
test
ed5b5f18-5c5d-488c-b467-00ca72b33ed3
main
['"fmt"', '"go/ast"', '"go/importer"', '"go/parser"', '"go/types"', '"log"']
github.com/test//tmp/repos/example/gotypes/typeandvalue/main.go
func main() { f, err := parser.ParseFile(fset, "hello.go", input, 0) if err != nil { log.Fatal(err) // parse error } conf := types.Config{Importer: importer.Default()} info := &types.Info{Types: make(map[ast.Expr]types.TypeAndValue)} if _, err := conf.Check("cmd/hello", fset, []*ast.File{f}, info); err != nil { log.Fatal(err) // type error } //!+inspect // f is a parsed, type-checked *ast.File. ast.Inspect(f, func(n ast.Node) bool { if expr, ok := n.(ast.Expr); ok { if tv, ok := info.Types[expr]; ok { fmt.Printf("%-24s\tmode: %s\n", nodeString(expr), mode(tv)) fmt.Printf("\t\t\t\ttype: %v\n", tv.Type) if tv.Value != nil { fmt.Printf("\t\t\t\tvalue: %v\n", tv.Value) } } } return true }) //!-inspect }
{'fset': 'token.NewFileSet()'}
main
function
test
3f84d7a5-a136-4231-931b-d527e0785cce
nodeString
['"bytes"', '"go/ast"', '"go/format"']
github.com/test//tmp/repos/example/gotypes/typeandvalue/main.go
func nodeString(n ast.Node) string { var buf bytes.Buffer format.Node(&buf, fset, n) return buf.String() }
{'fset': 'token.NewFileSet()'}
main
function
test
9488c523-0de2-48f8-99ba-f5ec3f915259
mode
['"go/types"']
github.com/test//tmp/repos/example/gotypes/typeandvalue/main.go
func mode(tv types.TypeAndValue) string { s := "" if tv.IsVoid() { s += ",void" } if tv.IsType() { s += ",type" } if tv.IsBuiltin() { s += ",builtin" } if tv.IsValue() { s += ",value" } if tv.IsNil() { s += ",nil" } if tv.Addressable() { s += ",addressable" } if tv.Assignable() { s += ",assignable" } if tv.HasOk() { s += ",ok" } return s[1:] }
main
file
test
74192b6e-40b4-4b9f-b866-56e6ea4a2610
hello.go
import ( "flag" "fmt" "log" "os" "golang.org/x/example/hello/reverse" )
github.com/test//tmp/repos/example/hello/hello.go
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Hello is a hello, world program, demonstrating // how to write a simple command-line program. // // Usage: // // hello [options] [name] // // The options are: // // -g greeting // Greet with the given greeting, instead of "Hello". // // -r // Greet in reverse. // // By default, hello greets the world. // If a name is specified, hello greets that name instead. package main import ( "flag" "fmt" "log" "os" "golang.org/x/example/hello/reverse" ) func usage() { fmt.Fprintf(os.Stderr, "usage: hello [options] [name]\n") flag.PrintDefaults() os.Exit(2) } var ( greeting = flag.String("g", "Hello", "Greet with `greeting`") reverseFlag = flag.Bool("r", false, "Greet in reverse") ) func main() { // Configure logging for a command-line program. log.SetFlags(0) log.SetPrefix("hello: ") // Parse flags. flag.Usage = usage flag.Parse() // Parse and validate arguments. name := "world" args := flag.Args() if len(args) >= 2 { usage() } if len(args) >= 1 { name = args[0] } if name == "" { // hello '' is an error log.Fatalf("invalid name %q", name) } // Run actual logic. if *reverseFlag { fmt.Printf("%s, %s!\n", reverse.String(*greeting), reverse.String(name)) return } fmt.Printf("%s, %s!\n", *greeting, name) }
package main
function
test
a7463a8a-a40c-4044-8919-788257ef04d2
usage
['"flag"', '"fmt"', '"os"']
github.com/test//tmp/repos/example/hello/hello.go
func usage() { fmt.Fprintf(os.Stderr, "usage: hello [options] [name]\n") flag.PrintDefaults() os.Exit(2) }
main
function
test
68f866a3-e13b-486d-8355-8b96813bf505
main
['"flag"', '"fmt"', '"log"', '"golang.org/x/example/hello/reverse"']
github.com/test//tmp/repos/example/hello/hello.go
func main() { // Configure logging for a command-line program. log.SetFlags(0) log.SetPrefix("hello: ") // Parse flags. flag.Usage = usage flag.Parse() // Parse and validate arguments. name := "world" args := flag.Args() if len(args) >= 2 { usage() } if len(args) >= 1 { name = args[0] } if name == "" { // hello '' is an error log.Fatalf("invalid name %q", name) } // Run actual logic. if *reverseFlag { fmt.Printf("%s, %s!\n", reverse.String(*greeting), reverse.String(name)) return } fmt.Printf("%s, %s!\n", *greeting, name) }
main
file
test
6c7cebfe-ee86-47e7-b13f-72292634e437
example_test.go
import ( "fmt" "golang.org/x/example/hello/reverse" )
github.com/test//tmp/repos/example/hello/reverse/example_test.go
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package reverse_test import ( "fmt" "golang.org/x/example/hello/reverse" ) func ExampleString() { fmt.Println(reverse.String("hello")) // Output: olleh }
package reverse_test
function
test
2b9ccb6e-be1c-490f-8675-23ba593b4996
ExampleString
['"fmt"', '"golang.org/x/example/hello/reverse"']
github.com/test//tmp/repos/example/hello/reverse/example_test.go
func ExampleString() { fmt.Println(reverse.String("hello")) // Output: olleh }
reverse_test
file
test
723b6dda-c644-4f81-a013-e7241b272856
reverse.go
github.com/test//tmp/repos/example/hello/reverse/reverse.go
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package reverse can reverse things, particularly strings. package reverse // String returns its argument string reversed rune-wise left to right. func String(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] } return string(r) }
package reverse
function
test
9d8118f7-40bb-4ecd-b929-65ecb1b7f367
String
github.com/test//tmp/repos/example/hello/reverse/reverse.go
func String(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] } return string(r) }
reverse
file
test
c40d9f92-db53-4678-a7db-4a25cc3fe522
reverse_test.go
import "testing"
github.com/test//tmp/repos/example/hello/reverse/reverse_test.go
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package reverse import "testing" func TestString(t *testing.T) { for _, c := range []struct { in, want string }{ {"Hello, world", "dlrow ,olleH"}, {"Hello, 世界", "界世 ,olleH"}, {"", ""}, } { got := String(c.in) if got != c.want { t.Errorf("String(%q) == %q, want %q", c.in, got, c.want) } } }
package reverse
function
test
674c7df4-b729-43e7-8e72-4b172ab9e9fa
TestString
github.com/test//tmp/repos/example/hello/reverse/reverse_test.go
func TestString(t *testing.T) { for _, c := range []struct { in, want string }{ {"Hello, world", "dlrow ,olleH"}, {"Hello, 世界", "界世 ,olleH"}, {"", ""}, } { got := String(c.in) if got != c.want { t.Errorf("String(%q) == %q, want %q", c.in, got, c.want) } } }
reverse
file
test
55fb6579-e23c-462d-af41-b6983f62fa89
server.go
import ( "flag" "fmt" "html" "log" "net/http" "os" "runtime/debug" "strings" )
github.com/test//tmp/repos/example/helloserver/server.go
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Hello is a simple hello, world demonstration web server. // // It serves version information on /version and answers // any other request like /name by saying "Hello, name!". // // See golang.org/x/example/outyet for a more sophisticated server. package main import ( "flag" "fmt" "html" "log" "net/http" "os" "runtime/debug" "strings" ) func usage() { fmt.Fprintf(os.Stderr, "usage: helloserver [options]\n") flag.PrintDefaults() os.Exit(2) } var ( greeting = flag.String("g", "Hello", "Greet with `greeting`") addr = flag.String("addr", "localhost:8080", "address to serve") ) func main() { // Parse flags. flag.Usage = usage flag.Parse() // Parse and validate arguments (none). args := flag.Args() if len(args) != 0 { usage() } // Register handlers. // All requests not otherwise mapped with go to greet. // /version is mapped specifically to version. http.HandleFunc("/", greet) http.HandleFunc("/version", version) log.Printf("serving http://%s\n", *addr) log.Fatal(http.ListenAndServe(*addr, nil)) } func version(w http.ResponseWriter, r *http.Request) { info, ok := debug.ReadBuildInfo() if !ok { http.Error(w, "no build information available", 500) return } fmt.Fprintf(w, "<!DOCTYPE html>\n<pre>\n") fmt.Fprintf(w, "%s\n", html.EscapeString(info.String())) } func greet(w http.ResponseWriter, r *http.Request) { name := strings.Trim(r.URL.Path, "/") if name == "" { name = "Gopher" } fmt.Fprintf(w, "<!DOCTYPE html>\n") fmt.Fprintf(w, "%s, %s!\n", *greeting, html.EscapeString(name)) }
package main
function
test
e578f785-5b60-4729-81de-d3856eeb67ad
usage
['"flag"', '"fmt"', '"os"']
github.com/test//tmp/repos/example/helloserver/server.go
func usage() { fmt.Fprintf(os.Stderr, "usage: helloserver [options]\n") flag.PrintDefaults() os.Exit(2) }
main
function
test
10cfb288-6c41-46ae-bc28-f003cc5999f2
main
['"flag"', '"log"', '"net/http"']
github.com/test//tmp/repos/example/helloserver/server.go
func main() { // Parse flags. flag.Usage = usage flag.Parse() // Parse and validate arguments (none). args := flag.Args() if len(args) != 0 { usage() } // Register handlers. // All requests not otherwise mapped with go to greet. // /version is mapped specifically to version. http.HandleFunc("/", greet) http.HandleFunc("/version", version) log.Printf("serving http://%s\n", *addr) log.Fatal(http.ListenAndServe(*addr, nil)) }
main
function
test
4d9091a6-5e5b-44f6-a7ec-b3a5eec2c9d4
version
['"fmt"', '"html"', '"net/http"', '"runtime/debug"']
github.com/test//tmp/repos/example/helloserver/server.go
func version(w http.ResponseWriter, r *http.Request) { info, ok := debug.ReadBuildInfo() if !ok { http.Error(w, "no build information available", 500) return } fmt.Fprintf(w, "<!DOCTYPE html>\n<pre>\n") fmt.Fprintf(w, "%s\n", html.EscapeString(info.String())) }
main
function
test
9a37ddbe-bdf1-4c86-b39b-9873c8b33ea4
greet
['"fmt"', '"html"', '"net/http"', '"strings"']
github.com/test//tmp/repos/example/helloserver/server.go
func greet(w http.ResponseWriter, r *http.Request) { name := strings.Trim(r.URL.Path, "/") if name == "" { name = "Gopher" } fmt.Fprintf(w, "<!DOCTYPE html>\n") fmt.Fprintf(w, "%s, %s!\n", *greeting, html.EscapeString(name)) }
main
file
test
a99e2da8-fedb-440a-b427-285766e388b0
weave.go
import ( "bufio" "bytes" "fmt" "log" "os" "path/filepath" "regexp" "strings" )
github.com/test//tmp/repos/example/internal/cmd/weave/weave.go
// The weave command is a simple preprocessor for markdown files. // It builds a table of contents and processes %include directives. // // Example usage: // // $ go run internal/cmd/weave go-types.md > README.md // // The weave command copies lines of the input file to standard output, with two // exceptions: // // If a line begins with "%toc", it is replaced with a table of contents // consisting of links to the top two levels of headers ("#" and "##"). // // If a line begins with "%include FILENAME TAG", it is replaced with the lines // of the file between lines containing "!+TAG" and "!-TAG". TAG can be omitted, // in which case the delimiters are simply "!+" and "!-". // // Before the included lines, a line of the form // // // go get PACKAGE // // is output, where PACKAGE is constructed from the module path, the // base name of the current directory, and the directory of FILENAME. // This caption can be suppressed by putting "-" as the final word of the %include line. package main import ( "bufio" "bytes" "fmt" "log" "os" "path/filepath" "regexp" "strings" ) func main() { log.SetFlags(0) log.SetPrefix("weave: ") if len(os.Args) != 2 { log.Fatal("usage: weave input.md\n") } f, err := os.Open(os.Args[1]) if err != nil { log.Fatal(err) } defer f.Close() wd, err := os.Getwd() if err != nil { log.Fatal(err) } curDir := filepath.Base(wd) fmt.Println("<!-- Autogenerated by weave; DO NOT EDIT -->") // Pass 1: extract table of contents. var toc []string in := bufio.NewScanner(f) for in.Scan() { line := in.Text() if line == "" || (line[0] != '#' && line[0] != '%') { continue } line = strings.TrimSpace(line) if line == "%toc" { toc = nil } else if strings.HasPrefix(line, "# ") || strings.HasPrefix(line, "## ") { words := strings.Fields(line) depth := len(words[0]) words = words[1:] text := strings.Join(words, " ") for i := range words { words[i] = strings.ToLower(words[i]) } line = fmt.Sprintf("%s1. [%s](#%s)", strings.Repeat("\t", depth-1), text, strings.Join(words, "-")) toc = append(toc, line) } } if in.Err() != nil { log.Fatal(in.Err()) } // Pass 2. if _, err := f.Seek(0, os.SEEK_SET); err != nil { log.Fatalf("can't rewind input: %v", err) } in = bufio.NewScanner(f) for in.Scan() { line := in.Text() switch { case strings.HasPrefix(line, "%toc"): // ToC for _, h := range toc { fmt.Println(h) } case strings.HasPrefix(line, "%include"): words := strings.Fields(line) if len(words) < 2 { log.Fatal(line) } filename := words[1] // Show caption unless '-' follows. if len(words) < 4 || words[3] != "-" { fmt.Printf(" // go get golang.org/x/example/%s/%s\n\n", curDir, filepath.Dir(filename)) } section := "" if len(words) > 2 { section = words[2] } s, err := include(filename, section) if err != nil { log.Fatal(err) } fmt.Println("```") fmt.Println(cleanListing(s)) // TODO(adonovan): escape /^```/ in s fmt.Println("```") default: fmt.Println(line) } } if in.Err() != nil { log.Fatal(in.Err()) } } // include processes an included file, and returns the included text. // Only lines between those matching !+tag and !-tag will be returned. // This is true even if tag=="". func include(file, tag string) (string, error) { f, err := os.Open(file) if err != nil { return "", err } defer f.Close() startre, err := regexp.Compile("!\\+" + tag + "$") if err != nil { return "", err } endre, err := regexp.Compile("!\\-" + tag + "$") if err != nil { return "", err } var text bytes.Buffer in := bufio.NewScanner(f) var on bool for in.Scan() { line := in.Text() switch { case startre.MatchString(line): on = true case endre.MatchString(line): on = false case on: text.WriteByte('\t') text.WriteString(line) text.WriteByte('\n') } } if in.Err() != nil { return "", in.Err() } if text.Len() == 0 { return "", fmt.Errorf("no lines of %s matched tag %q", file, tag) } return text.String(), nil } func isBlank(line string) bool { return strings.TrimSpace(line) == "" } func indented(line string) bool { return strings.HasPrefix(line, " ") || strings.HasPrefix(line, "\t") } // cleanListing removes entirely blank leading and trailing lines from // text, and removes n leading tabs. func cleanListing(text string) string { lines := strings.Split(text, "\n") // remove minimum number of leading tabs from all non-blank lines tabs := 999 for i, line := range lines { if strings.TrimSpace(line) == "" { lines[i] = "" } else { if n := leadingTabs(line); n < tabs { tabs = n } } } for i, line := range lines { if line != "" { line := line[tabs:] lines[i] = line // remove leading tabs } } // remove leading blank lines for len(lines) > 0 && lines[0] == "" { lines = lines[1:] } // remove trailing blank lines for len(lines) > 0 && lines[len(lines)-1] == "" { lines = lines[:len(lines)-1] } return strings.Join(lines, "\n") } func leadingTabs(s string) int { var i int for i = 0; i < len(s); i++ { if s[i] != '\t' { break } } return i }
package main
function
test
e34f0af7-7631-443a-aa9f-45cce35040c0
main
['"bufio"', '"fmt"', '"log"', '"os"', '"path/filepath"', '"strings"']
github.com/test//tmp/repos/example/internal/cmd/weave/weave.go
func main() { log.SetFlags(0) log.SetPrefix("weave: ") if len(os.Args) != 2 { log.Fatal("usage: weave input.md\n") } f, err := os.Open(os.Args[1]) if err != nil { log.Fatal(err) } defer f.Close() wd, err := os.Getwd() if err != nil { log.Fatal(err) } curDir := filepath.Base(wd) fmt.Println("<!-- Autogenerated by weave; DO NOT EDIT -->") // Pass 1: extract table of contents. var toc []string in := bufio.NewScanner(f) for in.Scan() { line := in.Text() if line == "" || (line[0] != '#' && line[0] != '%') { continue } line = strings.TrimSpace(line) if line == "%toc" { toc = nil } else if strings.HasPrefix(line, "# ") || strings.HasPrefix(line, "## ") { words := strings.Fields(line) depth := len(words[0]) words = words[1:] text := strings.Join(words, " ") for i := range words { words[i] = strings.ToLower(words[i]) } line = fmt.Sprintf("%s1. [%s](#%s)", strings.Repeat("\t", depth-1), text, strings.Join(words, "-")) toc = append(toc, line) } } if in.Err() != nil { log.Fatal(in.Err()) } // Pass 2. if _, err := f.Seek(0, os.SEEK_SET); err != nil { log.Fatalf("can't rewind input: %v", err) } in = bufio.NewScanner(f) for in.Scan() { line := in.Text() switch { case strings.HasPrefix(line, "%toc"): // ToC for _, h := range toc { fmt.Println(h) } case strings.HasPrefix(line, "%include"): words := strings.Fields(line) if len(words) < 2 { log.Fatal(line) } filename := words[1] // Show caption unless '-' follows. if len(words) < 4 || words[3] != "-" { fmt.Printf(" // go get golang.org/x/example/%s/%s\n\n", curDir, filepath.Dir(filename)) } section := "" if len(words) > 2 { section = words[2] } s, err := include(filename, section) if err != nil { log.Fatal(err) } fmt.Println("```") fmt.Println(cleanListing(s)) // TODO(adonovan): escape /^```/ in s fmt.Println("```") default: fmt.Println(line) } } if in.Err() != nil { log.Fatal(in.Err()) } }
main
function
test
f17e2ec8-b74b-49ab-a1a9-cf9939ccb2bb
include
['"bufio"', '"bytes"', '"fmt"', '"os"', '"regexp"']
github.com/test//tmp/repos/example/internal/cmd/weave/weave.go
func include(file, tag string) (string, error) { f, err := os.Open(file) if err != nil { return "", err } defer f.Close() startre, err := regexp.Compile("!\\+" + tag + "$") if err != nil { return "", err } endre, err := regexp.Compile("!\\-" + tag + "$") if err != nil { return "", err } var text bytes.Buffer in := bufio.NewScanner(f) var on bool for in.Scan() { line := in.Text() switch { case startre.MatchString(line): on = true case endre.MatchString(line): on = false case on: text.WriteByte('\t') text.WriteString(line) text.WriteByte('\n') } } if in.Err() != nil { return "", in.Err() } if text.Len() == 0 { return "", fmt.Errorf("no lines of %s matched tag %q", file, tag) } return text.String(), nil }
main
function
test
02c735d0-8373-4502-a994-c1b3b9a65815
isBlank
['"strings"']
github.com/test//tmp/repos/example/internal/cmd/weave/weave.go
func isBlank(line string) bool { return strings.TrimSpace(line) == "" }
main
function
test
7f5594ae-47b0-4362-98c3-be7cbeb05b06
indented
['"strings"']
github.com/test//tmp/repos/example/internal/cmd/weave/weave.go
func indented(line string) bool { return strings.HasPrefix(line, " ") || strings.HasPrefix(line, "\t") }
main
function
test
f2fbc275-35dc-45af-a3e5-97aa5b976a70
cleanListing
['"strings"']
github.com/test//tmp/repos/example/internal/cmd/weave/weave.go
func cleanListing(text string) string { lines := strings.Split(text, "\n") // remove minimum number of leading tabs from all non-blank lines tabs := 999 for i, line := range lines { if strings.TrimSpace(line) == "" { lines[i] = "" } else { if n := leadingTabs(line); n < tabs { tabs = n } } } for i, line := range lines { if line != "" { line := line[tabs:] lines[i] = line // remove leading tabs } } // remove leading blank lines for len(lines) > 0 && lines[0] == "" { lines = lines[1:] } // remove trailing blank lines for len(lines) > 0 && lines[len(lines)-1] == "" { lines = lines[:len(lines)-1] } return strings.Join(lines, "\n") }
main
function
test
e9d261fe-cf0e-4362-8aa1-f5a6dcf582b5
leadingTabs
github.com/test//tmp/repos/example/internal/cmd/weave/weave.go
func leadingTabs(s string) int { var i int for i = 0; i < len(s); i++ { if s[i] != '\t' { break } } return i }
main
file
test
03f5c1c5-b817-481a-8880-973a750e75d3
main.go
import ( "expvar" "flag" "fmt" "html/template" "log" "net/http" "sync" "time" )
github.com/test//tmp/repos/example/outyet/main.go
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Outyet is a web server that announces whether or not a particular Go version // has been tagged. package main import ( "expvar" "flag" "fmt" "html/template" "log" "net/http" "sync" "time" ) // Command-line flags. var ( httpAddr = flag.String("http", "localhost:8080", "Listen address") pollPeriod = flag.Duration("poll", 5*time.Second, "Poll period") version = flag.String("version", "1.4", "Go version") ) const baseChangeURL = "https://go.googlesource.com/go/+/" func main() { flag.Parse() changeURL := fmt.Sprintf("%sgo%s", baseChangeURL, *version) http.Handle("/", NewServer(*version, changeURL, *pollPeriod)) log.Printf("serving http://%s", *httpAddr) log.Fatal(http.ListenAndServe(*httpAddr, nil)) } // Exported variables for monitoring the server. // These are exported via HTTP as a JSON object at /debug/vars. var ( hitCount = expvar.NewInt("hitCount") pollCount = expvar.NewInt("pollCount") pollError = expvar.NewString("pollError") pollErrorCount = expvar.NewInt("pollErrorCount") ) // Server implements the outyet server. // It serves the user interface (it's an http.Handler) // and polls the remote repository for changes. type Server struct { version string url string period time.Duration mu sync.RWMutex // protects the yes variable yes bool } // NewServer returns an initialized outyet server. func NewServer(version, url string, period time.Duration) *Server { s := &Server{version: version, url: url, period: period} go s.poll() return s } // poll polls the change URL for the specified period until the tag exists. // Then it sets the Server's yes field true and exits. func (s *Server) poll() { for !isTagged(s.url) { pollSleep(s.period) } s.mu.Lock() s.yes = true s.mu.Unlock() pollDone() } // Hooks that may be overridden for integration tests. var ( pollSleep = time.Sleep pollDone = func() {} ) // isTagged makes an HTTP HEAD request to the given URL and reports whether it // returned a 200 OK response. func isTagged(url string) bool { pollCount.Add(1) r, err := http.Head(url) if err != nil { log.Print(err) pollError.Set(err.Error()) pollErrorCount.Add(1) return false } return r.StatusCode == http.StatusOK } // ServeHTTP implements the HTTP user interface. func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { hitCount.Add(1) s.mu.RLock() data := struct { URL string Version string Yes bool }{ s.url, s.version, s.yes, } s.mu.RUnlock() err := tmpl.Execute(w, data) if err != nil { log.Print(err) } } // tmpl is the HTML template that drives the user interface. var tmpl = template.Must(template.New("tmpl").Parse(` <!DOCTYPE html><html><body><center> <h2>Is Go {{.Version}} out yet?</h2> <h1> {{if .Yes}} <a href="{{.URL}}">YES!</a> {{else}} No. :-( {{end}} </h1> </center></body></html> `))
package main
function
test
4ff49c5e-a9a9-48a4-be08-6bb53dcad21c
main
['"flag"', '"fmt"', '"log"', '"net/http"']
github.com/test//tmp/repos/example/outyet/main.go
func main() { flag.Parse() changeURL := fmt.Sprintf("%sgo%s", baseChangeURL, *version) http.Handle("/", NewServer(*version, changeURL, *pollPeriod)) log.Printf("serving http://%s", *httpAddr) log.Fatal(http.ListenAndServe(*httpAddr, nil)) }
main
function
test
62042a1e-598e-42d4-bcdc-5f20aae2a2ed
NewServer
['"time"']
['Server']
github.com/test//tmp/repos/example/outyet/main.go
func NewServer(version, url string, period time.Duration) *Server { s := &Server{version: version, url: url, period: period} go s.poll() return s }
main
function
test
8418f2d5-d565-43c2-a21e-f0d6d3e575d0
poll
['Server']
github.com/test//tmp/repos/example/outyet/main.go
func (s *Server) poll() { for !isTagged(s.url) { pollSleep(s.period) } s.mu.Lock() s.yes = true s.mu.Unlock() pollDone() }
main
function
test
d20f51fd-a90b-4cde-b017-d15f723c9dba
isTagged
['"log"', '"net/http"']
github.com/test//tmp/repos/example/outyet/main.go
func isTagged(url string) bool { pollCount.Add(1) r, err := http.Head(url) if err != nil { log.Print(err) pollError.Set(err.Error()) pollErrorCount.Add(1) return false } return r.StatusCode == http.StatusOK }
main
function
test
2de530a7-b32e-462d-ba2e-2654a68adbce
ServeHTTP
['"log"', '"net/http"']
['Server']
github.com/test//tmp/repos/example/outyet/main.go
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { hitCount.Add(1) s.mu.RLock() data := struct { URL string Version string Yes bool }{ s.url, s.version, s.yes, } s.mu.RUnlock() err := tmpl.Execute(w, data) if err != nil { log.Print(err) } }
main
file
test
cafef87e-57d6-450b-8b88-b14bfb5cefc6
main_test.go
import ( "net/http" "net/http/httptest" "strings" "testing" "time" )
github.com/test//tmp/repos/example/outyet/main_test.go
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "net/http" "net/http/httptest" "strings" "testing" "time" ) // statusHandler is an http.Handler that writes an empty response using itself // as the response status code. type statusHandler int func (h *statusHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.WriteHeader(int(*h)) } func TestIsTagged(t *testing.T) { // Set up a fake "Google Code" web server reporting 404 not found. status := statusHandler(http.StatusNotFound) s := httptest.NewServer(&status) defer s.Close() if isTagged(s.URL) { t.Fatal("isTagged == true, want false") } // Change fake server status to 200 OK and try again. status = http.StatusOK if !isTagged(s.URL) { t.Fatal("isTagged == false, want true") } } func TestIntegration(t *testing.T) { status := statusHandler(http.StatusNotFound) ts := httptest.NewServer(&status) defer ts.Close() // Replace the pollSleep with a closure that we can block and unblock. sleep := make(chan bool) pollSleep = func(time.Duration) { sleep <- true sleep <- true } // Replace pollDone with a closure that will tell us when the poller is // exiting. done := make(chan bool) pollDone = func() { done <- true } // Put things as they were when the test finishes. defer func() { pollSleep = time.Sleep pollDone = func() {} }() s := NewServer("1.x", ts.URL, 1*time.Millisecond) <-sleep // Wait for poll loop to start sleeping. // Make first request to the server. r, _ := http.NewRequest("GET", "/", nil) w := httptest.NewRecorder() s.ServeHTTP(w, r) if b := w.Body.String(); !strings.Contains(b, "No.") { t.Fatalf("body = %s, want no", b) } status = http.StatusOK <-sleep // Permit poll loop to stop sleeping. <-done // Wait for poller to see the "OK" status and exit. // Make second request to the server. w = httptest.NewRecorder() s.ServeHTTP(w, r) if b := w.Body.String(); !strings.Contains(b, "YES!") { t.Fatalf("body = %q, want yes", b) } }
package main
function
test
c32c7dce-9e4d-497f-b544-eab314254271
ServeHTTP
['"net/http"']
github.com/test//tmp/repos/example/outyet/main_test.go
func (h *statusHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.WriteHeader(int(*h)) }
main
function
test
a9d9be59-de59-4dd1-ac23-818869d6a490
TestIsTagged
['"net/http"', '"net/http/httptest"', '"testing"']
github.com/test//tmp/repos/example/outyet/main_test.go
func TestIsTagged(t *testing.T) { // Set up a fake "Google Code" web server reporting 404 not found. status := statusHandler(http.StatusNotFound) s := httptest.NewServer(&status) defer s.Close() if isTagged(s.URL) { t.Fatal("isTagged == true, want false") } // Change fake server status to 200 OK and try again. status = http.StatusOK if !isTagged(s.URL) { t.Fatal("isTagged == false, want true") } }
main
function
test
059fdb04-2ac2-403c-b4c7-57970cf3916d
TestIntegration
['"net/http"', '"net/http/httptest"', '"strings"', '"testing"', '"time"']
github.com/test//tmp/repos/example/outyet/main_test.go
func TestIntegration(t *testing.T) { status := statusHandler(http.StatusNotFound) ts := httptest.NewServer(&status) defer ts.Close() // Replace the pollSleep with a closure that we can block and unblock. sleep := make(chan bool) pollSleep = func(time.Duration) { sleep <- true sleep <- true } // Replace pollDone with a closure that will tell us when the poller is // exiting. done := make(chan bool) pollDone = func() { done <- true } // Put things as they were when the test finishes. defer func() { pollSleep = time.Sleep pollDone = func() {} }() s := NewServer("1.x", ts.URL, 1*time.Millisecond) <-sleep // Wait for poll loop to start sleeping. // Make first request to the server. r, _ := http.NewRequest("GET", "/", nil) w := httptest.NewRecorder() s.ServeHTTP(w, r) if b := w.Body.String(); !strings.Contains(b, "No.") { t.Fatalf("body = %s, want no", b) } status = http.StatusOK <-sleep // Permit poll loop to stop sleeping. <-done // Wait for poller to see the "OK" status and exit. // Make second request to the server. w = httptest.NewRecorder() s.ServeHTTP(w, r) if b := w.Body.String(); !strings.Contains(b, "YES!") { t.Fatalf("body = %q, want yes", b) } }
main
file
test
b7a93d7b-8cfa-48da-ac8d-918c6b691dcb
json.go
import ( "encoding/json" "fmt" "mime" "net/http" )
github.com/test//tmp/repos/example/ragserver/ragserver-genkit/json.go
// Copyright 2024 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "encoding/json" "fmt" "mime" "net/http" ) // readRequestJSON expects req to have a JSON content type with a body that // contains a JSON-encoded value complying with the underlying type of target. // It populates target, or returns an error. func readRequestJSON(req *http.Request, target any) error { contentType := req.Header.Get("Content-Type") mediaType, _, err := mime.ParseMediaType(contentType) if err != nil { return err } if mediaType != "application/json" { return fmt.Errorf("expect application/json Content-Type, got %s", mediaType) } dec := json.NewDecoder(req.Body) dec.DisallowUnknownFields() return dec.Decode(target) } // renderJSON renders 'v' as JSON and writes it as a response into w. func renderJSON(w http.ResponseWriter, v any) { js, err := json.Marshal(v) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.Write(js) }
package main
function
test
355bac50-a60d-4bc8-927e-9211e2216337
readRequestJSON
['"encoding/json"', '"fmt"', '"mime"', '"net/http"']
github.com/test//tmp/repos/example/ragserver/ragserver-genkit/json.go
func readRequestJSON(req *http.Request, target any) error { contentType := req.Header.Get("Content-Type") mediaType, _, err := mime.ParseMediaType(contentType) if err != nil { return err } if mediaType != "application/json" { return fmt.Errorf("expect application/json Content-Type, got %s", mediaType) } dec := json.NewDecoder(req.Body) dec.DisallowUnknownFields() return dec.Decode(target) }
main
function
test
1efd70f2-ea5e-4160-8c4e-794673efcf93
renderJSON
['"encoding/json"', '"net/http"']
github.com/test//tmp/repos/example/ragserver/ragserver-genkit/json.go
func renderJSON(w http.ResponseWriter, v any) { js, err := json.Marshal(v) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.Write(js) }
main
file
test
c8597f88-b4bf-4416-8e0b-f5b89a9ec468
main.go
import ( "cmp" "context" "fmt" "log" "net/http" "os" "strings" "github.com/firebase/genkit/go/ai" "github.com/firebase/genkit/go/plugins/googleai" "github.com/firebase/genkit/go/plugins/weaviate" )
github.com/test//tmp/repos/example/ragserver/ragserver-genkit/main.go
// Copyright 2024 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Command ragserver is an HTTP server that implements RAG (Retrieval // Augmented Generation) using the Gemini model and Weaviate, which // are accessed using the Genkit package. See the accompanying README file for // additional details. package main import ( "cmp" "context" "fmt" "log" "net/http" "os" "strings" "github.com/firebase/genkit/go/ai" "github.com/firebase/genkit/go/plugins/googleai" "github.com/firebase/genkit/go/plugins/weaviate" ) const generativeModelName = "gemini-1.5-flash" const embeddingModelName = "text-embedding-004" // This is a standard Go HTTP server. Server state is in the ragServer struct. // The `main` function connects to the required services (Weaviate and Google // AI), initializes the server state and registers HTTP handlers. func main() { ctx := context.Background() err := googleai.Init(ctx, &googleai.Config{ APIKey: os.Getenv("GEMINI_API_KEY"), }) if err != nil { log.Fatal(err) } wvConfig := &weaviate.ClientConfig{ Scheme: "http", Addr: "localhost:" + cmp.Or(os.Getenv("WVPORT"), "9035"), } _, err = weaviate.Init(ctx, wvConfig) if err != nil { log.Fatal(err) } classConfig := &weaviate.ClassConfig{ Class: "Document", Embedder: googleai.Embedder(embeddingModelName), } indexer, retriever, err := weaviate.DefineIndexerAndRetriever(ctx, *classConfig) if err != nil { log.Fatal(err) } model := googleai.Model(generativeModelName) if model == nil { log.Fatal("unable to set up gemini-1.5-flash model") } server := &ragServer{ ctx: ctx, indexer: indexer, retriever: retriever, model: model, } mux := http.NewServeMux() mux.HandleFunc("POST /add/", server.addDocumentsHandler) mux.HandleFunc("POST /query/", server.queryHandler) port := cmp.Or(os.Getenv("SERVERPORT"), "9020") address := "localhost:" + port log.Println("listening on", address) log.Fatal(http.ListenAndServe(address, mux)) } type ragServer struct { ctx context.Context indexer ai.Indexer retriever ai.Retriever model ai.Model } func (rs *ragServer) addDocumentsHandler(w http.ResponseWriter, req *http.Request) { // Parse HTTP request from JSON. type document struct { Text string } type addRequest struct { Documents []document } ar := &addRequest{} err := readRequestJSON(req, ar) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // Convert request documents into Weaviate documents used for embedding. var wvDocs []*ai.Document for _, doc := range ar.Documents { wvDocs = append(wvDocs, ai.DocumentFromText(doc.Text, nil)) } // Index the requested documents. err = ai.Index(rs.ctx, rs.indexer, ai.WithIndexerDocs(wvDocs...)) if err != nil { http.Error(w, fmt.Errorf("indexing: %w", err).Error(), http.StatusInternalServerError) return } } func (rs *ragServer) queryHandler(w http.ResponseWriter, req *http.Request) { // Parse HTTP request from JSON. type queryRequest struct { Content string } qr := &queryRequest{} err := readRequestJSON(req, qr) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // Find the most similar documents using the retriever. resp, err := ai.Retrieve(rs.ctx, rs.retriever, ai.WithRetrieverDoc(ai.DocumentFromText(qr.Content, nil)), ai.WithRetrieverOpts(&weaviate.RetrieverOptions{ Count: 3, })) if err != nil { http.Error(w, fmt.Errorf("retrieval: %w", err).Error(), http.StatusInternalServerError) return } var docsContents []string for _, d := range resp.Documents { docsContents = append(docsContents, d.Content[0].Text) } // Create a RAG query for the LLM with the most relevant documents as // context. ragQuery := fmt.Sprintf(ragTemplateStr, qr.Content, strings.Join(docsContents, "\n")) genResp, err := ai.Generate(rs.ctx, rs.model, ai.WithTextPrompt(ragQuery)) if err != nil { log.Printf("calling generative model: %v", err.Error()) http.Error(w, "generative model error", http.StatusInternalServerError) return } if len(genResp.Candidates) != 1 { log.Printf("got %v candidates, expected 1", len(genResp.Candidates)) http.Error(w, "generative model error", http.StatusInternalServerError) return } renderJSON(w, genResp.Text()) } const ragTemplateStr = ` I will ask you a question and will provide some additional context information. Assume this context information is factual and correct, as part of internal documentation. If the question relates to the context, answer it using the context. If the question does not relate to the context, answer it as normal. For example, let's say the context has nothing in it about tropical flowers; then if I ask you about tropical flowers, just answer what you know about them without referring to the context. For example, if the context does mention minerology and I ask you about that, provide information from the context along with general knowledge. Question: %s Context: %s `
package main
function
test
3800456e-1f9e-413a-9147-845ca22d0af4
main
['"cmp"', '"context"', '"log"', '"net/http"', '"os"', '"github.com/firebase/genkit/go/plugins/googleai"', '"github.com/firebase/genkit/go/plugins/weaviate"']
['ragServer']
github.com/test//tmp/repos/example/ragserver/ragserver-genkit/main.go
func main() { ctx := context.Background() err := googleai.Init(ctx, &googleai.Config{ APIKey: os.Getenv("GEMINI_API_KEY"), }) if err != nil { log.Fatal(err) } wvConfig := &weaviate.ClientConfig{ Scheme: "http", Addr: "localhost:" + cmp.Or(os.Getenv("WVPORT"), "9035"), } _, err = weaviate.Init(ctx, wvConfig) if err != nil { log.Fatal(err) } classConfig := &weaviate.ClassConfig{ Class: "Document", Embedder: googleai.Embedder(embeddingModelName), } indexer, retriever, err := weaviate.DefineIndexerAndRetriever(ctx, *classConfig) if err != nil { log.Fatal(err) } model := googleai.Model(generativeModelName) if model == nil { log.Fatal("unable to set up gemini-1.5-flash model") } server := &ragServer{ ctx: ctx, indexer: indexer, retriever: retriever, model: model, } mux := http.NewServeMux() mux.HandleFunc("POST /add/", server.addDocumentsHandler) mux.HandleFunc("POST /query/", server.queryHandler) port := cmp.Or(os.Getenv("SERVERPORT"), "9020") address := "localhost:" + port log.Println("listening on", address) log.Fatal(http.ListenAndServe(address, mux)) }
main
function
test
b59466ed-7fcc-4cf0-bbd9-4250ae4cb873
addDocumentsHandler
['"fmt"', '"net/http"', '"github.com/firebase/genkit/go/ai"']
['ragServer']
github.com/test//tmp/repos/example/ragserver/ragserver-genkit/main.go
func (rs *ragServer) addDocumentsHandler(w http.ResponseWriter, req *http.Request) { // Parse HTTP request from JSON. type document struct { Text string } type addRequest struct { Documents []document } ar := &addRequest{} err := readRequestJSON(req, ar) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // Convert request documents into Weaviate documents used for embedding. var wvDocs []*ai.Document for _, doc := range ar.Documents { wvDocs = append(wvDocs, ai.DocumentFromText(doc.Text, nil)) } // Index the requested documents. err = ai.Index(rs.ctx, rs.indexer, ai.WithIndexerDocs(wvDocs...)) if err != nil { http.Error(w, fmt.Errorf("indexing: %w", err).Error(), http.StatusInternalServerError) return } }
main
function
test
e893523c-60e9-4846-be65-e456cdf7dc50
queryHandler
['"context"', '"fmt"', '"log"', '"net/http"', '"strings"', '"github.com/firebase/genkit/go/ai"', '"github.com/firebase/genkit/go/plugins/weaviate"']
['ragServer']
github.com/test//tmp/repos/example/ragserver/ragserver-genkit/main.go
func (rs *ragServer) queryHandler(w http.ResponseWriter, req *http.Request) { // Parse HTTP request from JSON. type queryRequest struct { Content string } qr := &queryRequest{} err := readRequestJSON(req, qr) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // Find the most similar documents using the retriever. resp, err := ai.Retrieve(rs.ctx, rs.retriever, ai.WithRetrieverDoc(ai.DocumentFromText(qr.Content, nil)), ai.WithRetrieverOpts(&weaviate.RetrieverOptions{ Count: 3, })) if err != nil { http.Error(w, fmt.Errorf("retrieval: %w", err).Error(), http.StatusInternalServerError) return } var docsContents []string for _, d := range resp.Documents { docsContents = append(docsContents, d.Content[0].Text) } // Create a RAG query for the LLM with the most relevant documents as // context. ragQuery := fmt.Sprintf(ragTemplateStr, qr.Content, strings.Join(docsContents, "\n")) genResp, err := ai.Generate(rs.ctx, rs.model, ai.WithTextPrompt(ragQuery)) if err != nil { log.Printf("calling generative model: %v", err.Error()) http.Error(w, "generative model error", http.StatusInternalServerError) return } if len(genResp.Candidates) != 1 { log.Printf("got %v candidates, expected 1", len(genResp.Candidates)) http.Error(w, "generative model error", http.StatusInternalServerError) return } renderJSON(w, genResp.Text()) }
main
file
test
9d49ac58-f975-4559-8c3c-833cc449dc4b
json.go
import ( "encoding/json" "fmt" "mime" "net/http" )
github.com/test//tmp/repos/example/ragserver/ragserver-langchaingo/json.go
// Copyright 2024 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "encoding/json" "fmt" "mime" "net/http" ) // readRequestJSON expects req to have a JSON content type with a body that // contains a JSON-encoded value complying with the underlying type of target. // It populates target, or returns an error. func readRequestJSON(req *http.Request, target any) error { contentType := req.Header.Get("Content-Type") mediaType, _, err := mime.ParseMediaType(contentType) if err != nil { return err } if mediaType != "application/json" { return fmt.Errorf("expect application/json Content-Type, got %s", mediaType) } dec := json.NewDecoder(req.Body) dec.DisallowUnknownFields() return dec.Decode(target) } // renderJSON renders 'v' as JSON and writes it as a response into w. func renderJSON(w http.ResponseWriter, v any) { js, err := json.Marshal(v) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.Write(js) }
package main
function
test
dee911c7-ada6-4a36-b146-8d1617ea1f0b
readRequestJSON
['"encoding/json"', '"fmt"', '"mime"', '"net/http"']
github.com/test//tmp/repos/example/ragserver/ragserver-langchaingo/json.go
func readRequestJSON(req *http.Request, target any) error { contentType := req.Header.Get("Content-Type") mediaType, _, err := mime.ParseMediaType(contentType) if err != nil { return err } if mediaType != "application/json" { return fmt.Errorf("expect application/json Content-Type, got %s", mediaType) } dec := json.NewDecoder(req.Body) dec.DisallowUnknownFields() return dec.Decode(target) }
main
function
test
1f886904-5ba3-4aa5-a8c5-b4a36ecb92d3
renderJSON
['"encoding/json"', '"net/http"']
github.com/test//tmp/repos/example/ragserver/ragserver-langchaingo/json.go
func renderJSON(w http.ResponseWriter, v any) { js, err := json.Marshal(v) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.Write(js) }
main
file
test
00b06ad0-f6be-44cf-a2f6-b7530eb2f3c3
main.go
import ( "cmp" "context" "fmt" "log" "net/http" "os" "strings" "github.com/tmc/langchaingo/embeddings" "github.com/tmc/langchaingo/llms" "github.com/tmc/langchaingo/llms/googleai" "github.com/tmc/langchaingo/schema" "github.com/tmc/langchaingo/vectorstores/weaviate" )
github.com/test//tmp/repos/example/ragserver/ragserver-langchaingo/main.go
// Copyright 2024 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Command ragserver is an HTTP server that implements RAG (Retrieval // Augmented Generation) using the Gemini model and Weaviate, which // are accessed using LangChainGo. See the accompanying README file for // additional details. package main import ( "cmp" "context" "fmt" "log" "net/http" "os" "strings" "github.com/tmc/langchaingo/embeddings" "github.com/tmc/langchaingo/llms" "github.com/tmc/langchaingo/llms/googleai" "github.com/tmc/langchaingo/schema" "github.com/tmc/langchaingo/vectorstores/weaviate" ) const generativeModelName = "gemini-1.5-flash" const embeddingModelName = "text-embedding-004" // This is a standard Go HTTP server. Server state is in the ragServer struct. // The `main` function connects to the required services (Weaviate and Google // AI), initializes the server state and registers HTTP handlers. func main() { ctx := context.Background() apiKey := os.Getenv("GEMINI_API_KEY") geminiClient, err := googleai.New(ctx, googleai.WithAPIKey(apiKey), googleai.WithDefaultEmbeddingModel(embeddingModelName)) if err != nil { log.Fatal(err) } emb, err := embeddings.NewEmbedder(geminiClient) if err != nil { log.Fatal(err) } wvStore, err := weaviate.New( weaviate.WithEmbedder(emb), weaviate.WithScheme("http"), weaviate.WithHost("localhost:"+cmp.Or(os.Getenv("WVPORT"), "9035")), weaviate.WithIndexName("Document"), ) server := &ragServer{ ctx: ctx, wvStore: wvStore, geminiClient: geminiClient, } mux := http.NewServeMux() mux.HandleFunc("POST /add/", server.addDocumentsHandler) mux.HandleFunc("POST /query/", server.queryHandler) port := cmp.Or(os.Getenv("SERVERPORT"), "9020") address := "localhost:" + port log.Println("listening on", address) log.Fatal(http.ListenAndServe(address, mux)) } type ragServer struct { ctx context.Context wvStore weaviate.Store geminiClient *googleai.GoogleAI } func (rs *ragServer) addDocumentsHandler(w http.ResponseWriter, req *http.Request) { // Parse HTTP request from JSON. type document struct { Text string } type addRequest struct { Documents []document } ar := &addRequest{} err := readRequestJSON(req, ar) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // Store documents and their embeddings in weaviate var wvDocs []schema.Document for _, doc := range ar.Documents { wvDocs = append(wvDocs, schema.Document{PageContent: doc.Text}) } _, err = rs.wvStore.AddDocuments(rs.ctx, wvDocs) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } } func (rs *ragServer) queryHandler(w http.ResponseWriter, req *http.Request) { // Parse HTTP request from JSON. type queryRequest struct { Content string } qr := &queryRequest{} err := readRequestJSON(req, qr) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // Find the most similar documents. docs, err := rs.wvStore.SimilaritySearch(rs.ctx, qr.Content, 3) if err != nil { http.Error(w, fmt.Errorf("similarity search: %w", err).Error(), http.StatusInternalServerError) return } var docsContents []string for _, doc := range docs { docsContents = append(docsContents, doc.PageContent) } // Create a RAG query for the LLM with the most relevant documents as // context. ragQuery := fmt.Sprintf(ragTemplateStr, qr.Content, strings.Join(docsContents, "\n")) respText, err := llms.GenerateFromSinglePrompt(rs.ctx, rs.geminiClient, ragQuery, llms.WithModel(generativeModelName)) if err != nil { log.Printf("calling generative model: %v", err.Error()) http.Error(w, "generative model error", http.StatusInternalServerError) return } renderJSON(w, respText) } const ragTemplateStr = ` I will ask you a question and will provide some additional context information. Assume this context information is factual and correct, as part of internal documentation. If the question relates to the context, answer it using the context. If the question does not relate to the context, answer it as normal. For example, let's say the context has nothing in it about tropical flowers; then if I ask you about tropical flowers, just answer what you know about them without referring to the context. For example, if the context does mention minerology and I ask you about that, provide information from the context along with general knowledge. Question: %s Context: %s `
package main
function
test
0d8e0bd9-093f-4293-8d1e-ac9c96a5dd71
main
['"cmp"', '"context"', '"log"', '"net/http"', '"os"', '"github.com/tmc/langchaingo/embeddings"', '"github.com/tmc/langchaingo/llms/googleai"', '"github.com/tmc/langchaingo/vectorstores/weaviate"']
['ragServer']
github.com/test//tmp/repos/example/ragserver/ragserver-langchaingo/main.go
func main() { ctx := context.Background() apiKey := os.Getenv("GEMINI_API_KEY") geminiClient, err := googleai.New(ctx, googleai.WithAPIKey(apiKey), googleai.WithDefaultEmbeddingModel(embeddingModelName)) if err != nil { log.Fatal(err) } emb, err := embeddings.NewEmbedder(geminiClient) if err != nil { log.Fatal(err) } wvStore, err := weaviate.New( weaviate.WithEmbedder(emb), weaviate.WithScheme("http"), weaviate.WithHost("localhost:"+cmp.Or(os.Getenv("WVPORT"), "9035")), weaviate.WithIndexName("Document"), ) server := &ragServer{ ctx: ctx, wvStore: wvStore, geminiClient: geminiClient, } mux := http.NewServeMux() mux.HandleFunc("POST /add/", server.addDocumentsHandler) mux.HandleFunc("POST /query/", server.queryHandler) port := cmp.Or(os.Getenv("SERVERPORT"), "9020") address := "localhost:" + port log.Println("listening on", address) log.Fatal(http.ListenAndServe(address, mux)) }
main
function
test
3e0fc818-4bb1-42ca-af27-3badf0f2e0c4
addDocumentsHandler
['"net/http"', '"github.com/tmc/langchaingo/embeddings"', '"github.com/tmc/langchaingo/schema"', '"github.com/tmc/langchaingo/vectorstores/weaviate"']
['ragServer']
github.com/test//tmp/repos/example/ragserver/ragserver-langchaingo/main.go
func (rs *ragServer) addDocumentsHandler(w http.ResponseWriter, req *http.Request) { // Parse HTTP request from JSON. type document struct { Text string } type addRequest struct { Documents []document } ar := &addRequest{} err := readRequestJSON(req, ar) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // Store documents and their embeddings in weaviate var wvDocs []schema.Document for _, doc := range ar.Documents { wvDocs = append(wvDocs, schema.Document{PageContent: doc.Text}) } _, err = rs.wvStore.AddDocuments(rs.ctx, wvDocs) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } }
main
function
test
6d7752b8-b68b-4ca6-a4f8-f3d5cbd43bee
queryHandler
['"context"', '"fmt"', '"log"', '"net/http"', '"strings"', '"github.com/tmc/langchaingo/llms"']
['ragServer']
github.com/test//tmp/repos/example/ragserver/ragserver-langchaingo/main.go
func (rs *ragServer) queryHandler(w http.ResponseWriter, req *http.Request) { // Parse HTTP request from JSON. type queryRequest struct { Content string } qr := &queryRequest{} err := readRequestJSON(req, qr) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // Find the most similar documents. docs, err := rs.wvStore.SimilaritySearch(rs.ctx, qr.Content, 3) if err != nil { http.Error(w, fmt.Errorf("similarity search: %w", err).Error(), http.StatusInternalServerError) return } var docsContents []string for _, doc := range docs { docsContents = append(docsContents, doc.PageContent) } // Create a RAG query for the LLM with the most relevant documents as // context. ragQuery := fmt.Sprintf(ragTemplateStr, qr.Content, strings.Join(docsContents, "\n")) respText, err := llms.GenerateFromSinglePrompt(rs.ctx, rs.geminiClient, ragQuery, llms.WithModel(generativeModelName)) if err != nil { log.Printf("calling generative model: %v", err.Error()) http.Error(w, "generative model error", http.StatusInternalServerError) return } renderJSON(w, respText) }
main
file
test
dd56731b-bc00-4a27-aaa2-066bacf67cd7
json.go
import ( "encoding/json" "fmt" "mime" "net/http" )
github.com/test//tmp/repos/example/ragserver/ragserver/json.go
// Copyright 2024 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "encoding/json" "fmt" "mime" "net/http" ) // readRequestJSON expects req to have a JSON content type with a body that // contains a JSON-encoded value complying with the underlying type of target. // It populates target, or returns an error. func readRequestJSON(req *http.Request, target any) error { contentType := req.Header.Get("Content-Type") mediaType, _, err := mime.ParseMediaType(contentType) if err != nil { return err } if mediaType != "application/json" { return fmt.Errorf("expect application/json Content-Type, got %s", mediaType) } dec := json.NewDecoder(req.Body) dec.DisallowUnknownFields() return dec.Decode(target) } // renderJSON renders 'v' as JSON and writes it as a response into w. func renderJSON(w http.ResponseWriter, v any) { js, err := json.Marshal(v) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.Write(js) }
package main
function
test
2e336fb2-8c0d-48ae-8e69-2958e49136df
readRequestJSON
['"encoding/json"', '"fmt"', '"mime"', '"net/http"']
github.com/test//tmp/repos/example/ragserver/ragserver/json.go
func readRequestJSON(req *http.Request, target any) error { contentType := req.Header.Get("Content-Type") mediaType, _, err := mime.ParseMediaType(contentType) if err != nil { return err } if mediaType != "application/json" { return fmt.Errorf("expect application/json Content-Type, got %s", mediaType) } dec := json.NewDecoder(req.Body) dec.DisallowUnknownFields() return dec.Decode(target) }
main
function
test
2bc8e2bc-0b0d-494a-9f80-7fd9b64a0ad5
renderJSON
['"encoding/json"', '"net/http"']
github.com/test//tmp/repos/example/ragserver/ragserver/json.go
func renderJSON(w http.ResponseWriter, v any) { js, err := json.Marshal(v) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.Write(js) }
main
file
test
a7322607-b6f7-46bf-aab0-dcb7300c7fd1
main.go
import ( "cmp" "context" "fmt" "log" "net/http" "os" "strings" "github.com/google/generative-ai-go/genai" "github.com/weaviate/weaviate-go-client/v4/weaviate" "github.com/weaviate/weaviate-go-client/v4/weaviate/graphql" "github.com/weaviate/weaviate/entities/models" "google.golang.org/api/option" )
github.com/test//tmp/repos/example/ragserver/ragserver/main.go
// Copyright 2024 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Command ragserver is an HTTP server that implements RAG (Retrieval // Augmented Generation) using the Gemini model and Weaviate. See the // accompanying README file for additional details. package main import ( "cmp" "context" "fmt" "log" "net/http" "os" "strings" "github.com/google/generative-ai-go/genai" "github.com/weaviate/weaviate-go-client/v4/weaviate" "github.com/weaviate/weaviate-go-client/v4/weaviate/graphql" "github.com/weaviate/weaviate/entities/models" "google.golang.org/api/option" ) const generativeModelName = "gemini-1.5-flash" const embeddingModelName = "text-embedding-004" // This is a standard Go HTTP server. Server state is in the ragServer struct. // The `main` function connects to the required services (Weaviate and Google // AI), initializes the server state and registers HTTP handlers. func main() { ctx := context.Background() wvClient, err := initWeaviate(ctx) if err != nil { log.Fatal(err) } apiKey := os.Getenv("GEMINI_API_KEY") genaiClient, err := genai.NewClient(ctx, option.WithAPIKey(apiKey)) if err != nil { log.Fatal(err) } defer genaiClient.Close() server := &ragServer{ ctx: ctx, wvClient: wvClient, genModel: genaiClient.GenerativeModel(generativeModelName), embModel: genaiClient.EmbeddingModel(embeddingModelName), } mux := http.NewServeMux() mux.HandleFunc("POST /add/", server.addDocumentsHandler) mux.HandleFunc("POST /query/", server.queryHandler) port := cmp.Or(os.Getenv("SERVERPORT"), "9020") address := "localhost:" + port log.Println("listening on", address) log.Fatal(http.ListenAndServe(address, mux)) } type ragServer struct { ctx context.Context wvClient *weaviate.Client genModel *genai.GenerativeModel embModel *genai.EmbeddingModel } func (rs *ragServer) addDocumentsHandler(w http.ResponseWriter, req *http.Request) { // Parse HTTP request from JSON. type document struct { Text string } type addRequest struct { Documents []document } ar := &addRequest{} err := readRequestJSON(req, ar) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // Use the batch embedding API to embed all documents at once. batch := rs.embModel.NewBatch() for _, doc := range ar.Documents { batch.AddContent(genai.Text(doc.Text)) } log.Printf("invoking embedding model with %v documents", len(ar.Documents)) rsp, err := rs.embModel.BatchEmbedContents(rs.ctx, batch) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } if len(rsp.Embeddings) != len(ar.Documents) { http.Error(w, "embedded batch size mismatch", http.StatusInternalServerError) return } // Convert our documents - along with their embedding vectors - into types // used by the Weaviate client library. objects := make([]*models.Object, len(ar.Documents)) for i, doc := range ar.Documents { objects[i] = &models.Object{ Class: "Document", Properties: map[string]any{ "text": doc.Text, }, Vector: rsp.Embeddings[i].Values, } } // Store documents with embeddings in the Weaviate DB. log.Printf("storing %v objects in weaviate", len(objects)) _, err = rs.wvClient.Batch().ObjectsBatcher().WithObjects(objects...).Do(rs.ctx) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } } func (rs *ragServer) queryHandler(w http.ResponseWriter, req *http.Request) { // Parse HTTP request from JSON. type queryRequest struct { Content string } qr := &queryRequest{} err := readRequestJSON(req, qr) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // Embed the query contents. rsp, err := rs.embModel.EmbedContent(rs.ctx, genai.Text(qr.Content)) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // Search weaviate to find the most relevant (closest in vector space) // documents to the query. gql := rs.wvClient.GraphQL() result, err := gql.Get(). WithNearVector( gql.NearVectorArgBuilder().WithVector(rsp.Embedding.Values)). WithClassName("Document"). WithFields(graphql.Field{Name: "text"}). WithLimit(3). Do(rs.ctx) if werr := combinedWeaviateError(result, err); werr != nil { http.Error(w, werr.Error(), http.StatusInternalServerError) return } contents, err := decodeGetResults(result) if err != nil { http.Error(w, fmt.Errorf("reading weaviate response: %w", err).Error(), http.StatusInternalServerError) return } // Create a RAG query for the LLM with the most relevant documents as // context. ragQuery := fmt.Sprintf(ragTemplateStr, qr.Content, strings.Join(contents, "\n")) resp, err := rs.genModel.GenerateContent(rs.ctx, genai.Text(ragQuery)) if err != nil { log.Printf("calling generative model: %v", err.Error()) http.Error(w, "generative model error", http.StatusInternalServerError) return } if len(resp.Candidates) != 1 { log.Printf("got %v candidates, expected 1", len(resp.Candidates)) http.Error(w, "generative model error", http.StatusInternalServerError) return } var respTexts []string for _, part := range resp.Candidates[0].Content.Parts { if pt, ok := part.(genai.Text); ok { respTexts = append(respTexts, string(pt)) } else { log.Printf("bad type of part: %v", pt) http.Error(w, "generative model error", http.StatusInternalServerError) return } } renderJSON(w, strings.Join(respTexts, "\n")) } const ragTemplateStr = ` I will ask you a question and will provide some additional context information. Assume this context information is factual and correct, as part of internal documentation. If the question relates to the context, answer it using the context. If the question does not relate to the context, answer it as normal. For example, let's say the context has nothing in it about tropical flowers; then if I ask you about tropical flowers, just answer what you know about them without referring to the context. For example, if the context does mention minerology and I ask you about that, provide information from the context along with general knowledge. Question: %s Context: %s ` // decodeGetResults decodes the result returned by Weaviate's GraphQL Get // query; these are returned as a nested map[string]any (just like JSON // unmarshaled into a map[string]any). We have to extract all document contents // as a list of strings. func decodeGetResults(result *models.GraphQLResponse) ([]string, error) { data, ok := result.Data["Get"] if !ok { return nil, fmt.Errorf("Get key not found in result") } doc, ok := data.(map[string]any) if !ok { return nil, fmt.Errorf("Get key unexpected type") } slc, ok := doc["Document"].([]any) if !ok { return nil, fmt.Errorf("Document is not a list of results") } var out []string for _, s := range slc { smap, ok := s.(map[string]any) if !ok { return nil, fmt.Errorf("invalid element in list of documents") } s, ok := smap["text"].(string) if !ok { return nil, fmt.Errorf("expected string in list of documents") } out = append(out, s) } return out, nil }
package main
function
test
d5b04245-bdd4-43c3-a6a2-5fc4f3672718
main
['"cmp"', '"context"', '"log"', '"net/http"', '"os"', '"github.com/google/generative-ai-go/genai"', '"google.golang.org/api/option"']
['ragServer']
github.com/test//tmp/repos/example/ragserver/ragserver/main.go
func main() { ctx := context.Background() wvClient, err := initWeaviate(ctx) if err != nil { log.Fatal(err) } apiKey := os.Getenv("GEMINI_API_KEY") genaiClient, err := genai.NewClient(ctx, option.WithAPIKey(apiKey)) if err != nil { log.Fatal(err) } defer genaiClient.Close() server := &ragServer{ ctx: ctx, wvClient: wvClient, genModel: genaiClient.GenerativeModel(generativeModelName), embModel: genaiClient.EmbeddingModel(embeddingModelName), } mux := http.NewServeMux() mux.HandleFunc("POST /add/", server.addDocumentsHandler) mux.HandleFunc("POST /query/", server.queryHandler) port := cmp.Or(os.Getenv("SERVERPORT"), "9020") address := "localhost:" + port log.Println("listening on", address) log.Fatal(http.ListenAndServe(address, mux)) }
main
function
test
251dbf12-7ad9-4616-a07d-427fcbe7f8e7
addDocumentsHandler
['"log"', '"net/http"', '"github.com/google/generative-ai-go/genai"', '"github.com/weaviate/weaviate-go-client/v4/weaviate"', '"github.com/weaviate/weaviate/entities/models"']
['ragServer']
github.com/test//tmp/repos/example/ragserver/ragserver/main.go
func (rs *ragServer) addDocumentsHandler(w http.ResponseWriter, req *http.Request) { // Parse HTTP request from JSON. type document struct { Text string } type addRequest struct { Documents []document } ar := &addRequest{} err := readRequestJSON(req, ar) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // Use the batch embedding API to embed all documents at once. batch := rs.embModel.NewBatch() for _, doc := range ar.Documents { batch.AddContent(genai.Text(doc.Text)) } log.Printf("invoking embedding model with %v documents", len(ar.Documents)) rsp, err := rs.embModel.BatchEmbedContents(rs.ctx, batch) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } if len(rsp.Embeddings) != len(ar.Documents) { http.Error(w, "embedded batch size mismatch", http.StatusInternalServerError) return } // Convert our documents - along with their embedding vectors - into types // used by the Weaviate client library. objects := make([]*models.Object, len(ar.Documents)) for i, doc := range ar.Documents { objects[i] = &models.Object{ Class: "Document", Properties: map[string]any{ "text": doc.Text, }, Vector: rsp.Embeddings[i].Values, } } // Store documents with embeddings in the Weaviate DB. log.Printf("storing %v objects in weaviate", len(objects)) _, err = rs.wvClient.Batch().ObjectsBatcher().WithObjects(objects...).Do(rs.ctx) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } }
main
function
test
4b107d7e-bb57-430e-a148-4fe766dfaa3c
queryHandler
['"context"', '"fmt"', '"log"', '"net/http"', '"strings"', '"github.com/google/generative-ai-go/genai"', '"github.com/weaviate/weaviate-go-client/v4/weaviate"', '"github.com/weaviate/weaviate-go-client/v4/weaviate/graphql"']
['ragServer']
github.com/test//tmp/repos/example/ragserver/ragserver/main.go
func (rs *ragServer) queryHandler(w http.ResponseWriter, req *http.Request) { // Parse HTTP request from JSON. type queryRequest struct { Content string } qr := &queryRequest{} err := readRequestJSON(req, qr) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // Embed the query contents. rsp, err := rs.embModel.EmbedContent(rs.ctx, genai.Text(qr.Content)) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // Search weaviate to find the most relevant (closest in vector space) // documents to the query. gql := rs.wvClient.GraphQL() result, err := gql.Get(). WithNearVector( gql.NearVectorArgBuilder().WithVector(rsp.Embedding.Values)). WithClassName("Document"). WithFields(graphql.Field{Name: "text"}). WithLimit(3). Do(rs.ctx) if werr := combinedWeaviateError(result, err); werr != nil { http.Error(w, werr.Error(), http.StatusInternalServerError) return } contents, err := decodeGetResults(result) if err != nil { http.Error(w, fmt.Errorf("reading weaviate response: %w", err).Error(), http.StatusInternalServerError) return } // Create a RAG query for the LLM with the most relevant documents as // context. ragQuery := fmt.Sprintf(ragTemplateStr, qr.Content, strings.Join(contents, "\n")) resp, err := rs.genModel.GenerateContent(rs.ctx, genai.Text(ragQuery)) if err != nil { log.Printf("calling generative model: %v", err.Error()) http.Error(w, "generative model error", http.StatusInternalServerError) return } if len(resp.Candidates) != 1 { log.Printf("got %v candidates, expected 1", len(resp.Candidates)) http.Error(w, "generative model error", http.StatusInternalServerError) return } var respTexts []string for _, part := range resp.Candidates[0].Content.Parts { if pt, ok := part.(genai.Text); ok { respTexts = append(respTexts, string(pt)) } else { log.Printf("bad type of part: %v", pt) http.Error(w, "generative model error", http.StatusInternalServerError) return } } renderJSON(w, strings.Join(respTexts, "\n")) }
main
function
test
ce3eb781-4e04-4bb0-8026-43c365013810
decodeGetResults
['"fmt"', '"github.com/weaviate/weaviate/entities/models"']
github.com/test//tmp/repos/example/ragserver/ragserver/main.go
func decodeGetResults(result *models.GraphQLResponse) ([]string, error) { data, ok := result.Data["Get"] if !ok { return nil, fmt.Errorf("Get key not found in result") } doc, ok := data.(map[string]any) if !ok { return nil, fmt.Errorf("Get key unexpected type") } slc, ok := doc["Document"].([]any) if !ok { return nil, fmt.Errorf("Document is not a list of results") } var out []string for _, s := range slc { smap, ok := s.(map[string]any) if !ok { return nil, fmt.Errorf("invalid element in list of documents") } s, ok := smap["text"].(string) if !ok { return nil, fmt.Errorf("expected string in list of documents") } out = append(out, s) } return out, nil }
main
file
test
713c103e-2f06-4354-91be-95619b00487a
weaviate.go
import ( "cmp" "context" "fmt" "os" "github.com/weaviate/weaviate-go-client/v4/weaviate" "github.com/weaviate/weaviate/entities/models" )
github.com/test//tmp/repos/example/ragserver/ragserver/weaviate.go
// Copyright 2024 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main // Utilities for working with Weaviate. import ( "cmp" "context" "fmt" "os" "github.com/weaviate/weaviate-go-client/v4/weaviate" "github.com/weaviate/weaviate/entities/models" ) // initWeaviate initializes a weaviate client for our application. func initWeaviate(ctx context.Context) (*weaviate.Client, error) { client, err := weaviate.NewClient(weaviate.Config{ Host: "localhost:" + cmp.Or(os.Getenv("WVPORT"), "9035"), Scheme: "http", }) if err != nil { return nil, fmt.Errorf("initializing weaviate: %w", err) } // Create a new class (collection) in weaviate if it doesn't exist yet. cls := &models.Class{ Class: "Document", Vectorizer: "none", } exists, err := client.Schema().ClassExistenceChecker().WithClassName(cls.Class).Do(ctx) if err != nil { return nil, fmt.Errorf("weaviate error: %w", err) } if !exists { err = client.Schema().ClassCreator().WithClass(cls).Do(ctx) if err != nil { return nil, fmt.Errorf("weaviate error: %w", err) } } return client, nil } // combinedWeaviateError generates an error if err is non-nil or result has // errors, and returns an error (or nil if there's no error). It's useful for // the results of the Weaviate GraphQL API's "Do" calls. func combinedWeaviateError(result *models.GraphQLResponse, err error) error { if err != nil { return err } if len(result.Errors) != 0 { var ss []string for _, e := range result.Errors { ss = append(ss, e.Message) } return fmt.Errorf("weaviate error: %v", ss) } return nil }
package main
function
test
274389b8-2b90-4bb9-af11-7991ea87338d
initWeaviate
['"cmp"', '"context"', '"fmt"', '"os"', '"github.com/weaviate/weaviate-go-client/v4/weaviate"', '"github.com/weaviate/weaviate/entities/models"']
github.com/test//tmp/repos/example/ragserver/ragserver/weaviate.go
func initWeaviate(ctx context.Context) (*weaviate.Client, error) { client, err := weaviate.NewClient(weaviate.Config{ Host: "localhost:" + cmp.Or(os.Getenv("WVPORT"), "9035"), Scheme: "http", }) if err != nil { return nil, fmt.Errorf("initializing weaviate: %w", err) } // Create a new class (collection) in weaviate if it doesn't exist yet. cls := &models.Class{ Class: "Document", Vectorizer: "none", } exists, err := client.Schema().ClassExistenceChecker().WithClassName(cls.Class).Do(ctx) if err != nil { return nil, fmt.Errorf("weaviate error: %w", err) } if !exists { err = client.Schema().ClassCreator().WithClass(cls).Do(ctx) if err != nil { return nil, fmt.Errorf("weaviate error: %w", err) } } return client, nil }
main
function
test
48994825-903f-49a7-8c73-70b8c1ae57ba
combinedWeaviateError
['"fmt"', '"github.com/weaviate/weaviate-go-client/v4/weaviate"', '"github.com/weaviate/weaviate/entities/models"']
github.com/test//tmp/repos/example/ragserver/ragserver/weaviate.go
func combinedWeaviateError(result *models.GraphQLResponse, err error) error { if err != nil { return err } if len(result.Errors) != 0 { var ss []string for _, e := range result.Errors { ss = append(ss, e.Message) } return fmt.Errorf("weaviate error: %v", ss) } return nil }
main
file
test
ddc1de38-0d0d-4ede-95b7-11594bf3246c
indent_handler.go
import ( "context" "fmt" "io" "log/slog" "runtime" "sync" "time" )
github.com/test//tmp/repos/example/slog-handler-guide/indenthandler1/indent_handler.go
//go:build go1.21 package indenthandler import ( "context" "fmt" "io" "log/slog" "runtime" "sync" "time" ) // !+types type IndentHandler struct { opts Options // TODO: state for WithGroup and WithAttrs mu *sync.Mutex out io.Writer } type Options struct { // Level reports the minimum level to log. // Levels with lower levels are discarded. // If nil, the Handler uses [slog.LevelInfo]. Level slog.Leveler } func New(out io.Writer, opts *Options) *IndentHandler { h := &IndentHandler{out: out, mu: &sync.Mutex{}} if opts != nil { h.opts = *opts } if h.opts.Level == nil { h.opts.Level = slog.LevelInfo } return h } //!-types // !+enabled func (h *IndentHandler) Enabled(ctx context.Context, level slog.Level) bool { return level >= h.opts.Level.Level() } //!-enabled func (h *IndentHandler) WithGroup(name string) slog.Handler { // TODO: implement. return h } func (h *IndentHandler) WithAttrs(attrs []slog.Attr) slog.Handler { // TODO: implement. return h } // !+handle func (h *IndentHandler) Handle(ctx context.Context, r slog.Record) error { buf := make([]byte, 0, 1024) if !r.Time.IsZero() { buf = h.appendAttr(buf, slog.Time(slog.TimeKey, r.Time), 0) } buf = h.appendAttr(buf, slog.Any(slog.LevelKey, r.Level), 0) if r.PC != 0 { fs := runtime.CallersFrames([]uintptr{r.PC}) f, _ := fs.Next() buf = h.appendAttr(buf, slog.String(slog.SourceKey, fmt.Sprintf("%s:%d", f.File, f.Line)), 0) } buf = h.appendAttr(buf, slog.String(slog.MessageKey, r.Message), 0) indentLevel := 0 // TODO: output the Attrs and groups from WithAttrs and WithGroup. r.Attrs(func(a slog.Attr) bool { buf = h.appendAttr(buf, a, indentLevel) return true }) buf = append(buf, "---\n"...) h.mu.Lock() defer h.mu.Unlock() _, err := h.out.Write(buf) return err } //!-handle // !+appendAttr func (h *IndentHandler) appendAttr(buf []byte, a slog.Attr, indentLevel int) []byte { // Resolve the Attr's value before doing anything else. a.Value = a.Value.Resolve() // Ignore empty Attrs. if a.Equal(slog.Attr{}) { return buf } // Indent 4 spaces per level. buf = fmt.Appendf(buf, "%*s", indentLevel*4, "") switch a.Value.Kind() { case slog.KindString: // Quote string values, to make them easy to parse. buf = fmt.Appendf(buf, "%s: %q\n", a.Key, a.Value.String()) case slog.KindTime: // Write times in a standard way, without the monotonic time. buf = fmt.Appendf(buf, "%s: %s\n", a.Key, a.Value.Time().Format(time.RFC3339Nano)) case slog.KindGroup: attrs := a.Value.Group() // Ignore empty groups. if len(attrs) == 0 { return buf } // If the key is non-empty, write it out and indent the rest of the attrs. // Otherwise, inline the attrs. if a.Key != "" { buf = fmt.Appendf(buf, "%s:\n", a.Key) indentLevel++ } for _, ga := range attrs { buf = h.appendAttr(buf, ga, indentLevel) } default: buf = fmt.Appendf(buf, "%s: %s\n", a.Key, a.Value) } return buf } //!-appendAttr
package indenthandler
function
test
58281b7b-30de-4770-b397-481dd40124c2
New
['"io"', '"log/slog"', '"sync"']
['IndentHandler', 'Options']
github.com/test//tmp/repos/example/slog-handler-guide/indenthandler1/indent_handler.go
func New(out io.Writer, opts *Options) *IndentHandler { h := &IndentHandler{out: out, mu: &sync.Mutex{}} if opts != nil { h.opts = *opts } if h.opts.Level == nil { h.opts.Level = slog.LevelInfo } return h }
indenthandler
function
test
9378f63f-2805-4e16-99bd-94be7beedeef
Enabled
['"context"', '"log/slog"']
['IndentHandler']
github.com/test//tmp/repos/example/slog-handler-guide/indenthandler1/indent_handler.go
func (h *IndentHandler) Enabled(ctx context.Context, level slog.Level) bool { return level >= h.opts.Level.Level() }
indenthandler
function
test
5b584411-f588-486e-a449-401e348bc66e
WithGroup
['"log/slog"']
['IndentHandler']
github.com/test//tmp/repos/example/slog-handler-guide/indenthandler1/indent_handler.go
func (h *IndentHandler) WithGroup(name string) slog.Handler { // TODO: implement. return h }
indenthandler
function
test
e16254e1-fe30-47a4-ad15-a451e3b3c16f
WithAttrs
['"log/slog"']
['IndentHandler']
github.com/test//tmp/repos/example/slog-handler-guide/indenthandler1/indent_handler.go
func (h *IndentHandler) WithAttrs(attrs []slog.Attr) slog.Handler { // TODO: implement. return h }
indenthandler
function
test
166da4ce-afbf-4e6a-b8f6-a63660af5db4
Handle
['"context"', '"fmt"', '"log/slog"', '"runtime"']
['IndentHandler']
github.com/test//tmp/repos/example/slog-handler-guide/indenthandler1/indent_handler.go
func (h *IndentHandler) Handle(ctx context.Context, r slog.Record) error { buf := make([]byte, 0, 1024) if !r.Time.IsZero() { buf = h.appendAttr(buf, slog.Time(slog.TimeKey, r.Time), 0) } buf = h.appendAttr(buf, slog.Any(slog.LevelKey, r.Level), 0) if r.PC != 0 { fs := runtime.CallersFrames([]uintptr{r.PC}) f, _ := fs.Next() buf = h.appendAttr(buf, slog.String(slog.SourceKey, fmt.Sprintf("%s:%d", f.File, f.Line)), 0) } buf = h.appendAttr(buf, slog.String(slog.MessageKey, r.Message), 0) indentLevel := 0 // TODO: output the Attrs and groups from WithAttrs and WithGroup. r.Attrs(func(a slog.Attr) bool { buf = h.appendAttr(buf, a, indentLevel) return true }) buf = append(buf, "---\n"...) h.mu.Lock() defer h.mu.Unlock() _, err := h.out.Write(buf) return err }
indenthandler
function
test
8089542e-ffa1-40d8-abb1-a9d18ce47b54
appendAttr
['"fmt"', '"log/slog"', '"time"']
['IndentHandler']
github.com/test//tmp/repos/example/slog-handler-guide/indenthandler1/indent_handler.go
func (h *IndentHandler) appendAttr(buf []byte, a slog.Attr, indentLevel int) []byte { // Resolve the Attr's value before doing anything else. a.Value = a.Value.Resolve() // Ignore empty Attrs. if a.Equal(slog.Attr{}) { return buf } // Indent 4 spaces per level. buf = fmt.Appendf(buf, "%*s", indentLevel*4, "") switch a.Value.Kind() { case slog.KindString: // Quote string values, to make them easy to parse. buf = fmt.Appendf(buf, "%s: %q\n", a.Key, a.Value.String()) case slog.KindTime: // Write times in a standard way, without the monotonic time. buf = fmt.Appendf(buf, "%s: %s\n", a.Key, a.Value.Time().Format(time.RFC3339Nano)) case slog.KindGroup: attrs := a.Value.Group() // Ignore empty groups. if len(attrs) == 0 { return buf } // If the key is non-empty, write it out and indent the rest of the attrs. // Otherwise, inline the attrs. if a.Key != "" { buf = fmt.Appendf(buf, "%s:\n", a.Key) indentLevel++ } for _, ga := range attrs { buf = h.appendAttr(buf, ga, indentLevel) } default: buf = fmt.Appendf(buf, "%s: %s\n", a.Key, a.Value) } return buf }
indenthandler
file
test
8f82a0f6-8d0d-49ca-9238-b9aaffd1c4e2
indent_handler_test.go
import ( "bytes" "regexp" "testing" "log/slog" )
github.com/test//tmp/repos/example/slog-handler-guide/indenthandler1/indent_handler_test.go
//go:build go1.21 package indenthandler import ( "bytes" "regexp" "testing" "log/slog" ) func Test(t *testing.T) { var buf bytes.Buffer l := slog.New(New(&buf, nil)) l.Info("hello", "a", 1, "b", true, "c", 3.14, slog.Group("g", "h", 1, "i", 2), "d", "NO") got := buf.String() wantre := `time: [-0-9T:.]+Z? level: INFO source: ".*/indent_handler_test.go:\d+" msg: "hello" a: 1 b: true c: 3.14 g: h: 1 i: 2 d: "NO" ` re := regexp.MustCompile(wantre) if !re.MatchString(got) { t.Errorf("\ngot:\n%q\nwant:\n%q", got, wantre) } buf.Reset() l.Debug("test") if got := buf.Len(); got != 0 { t.Errorf("got buf.Len() = %d, want 0", got) } }
package indenthandler
function
test
a69b8315-7ccb-4777-ad12-b53a8ecf72ea
Test
['"bytes"', '"regexp"', '"testing"', '"log/slog"']
github.com/test//tmp/repos/example/slog-handler-guide/indenthandler1/indent_handler_test.go
func Test(t *testing.T) { var buf bytes.Buffer l := slog.New(New(&buf, nil)) l.Info("hello", "a", 1, "b", true, "c", 3.14, slog.Group("g", "h", 1, "i", 2), "d", "NO") got := buf.String() wantre := `time: [-0-9T:.]+Z? level: INFO source: ".*/indent_handler_test.go:\d+" msg: "hello" a: 1 b: true c: 3.14 g: h: 1 i: 2 d: "NO" ` re := regexp.MustCompile(wantre) if !re.MatchString(got) { t.Errorf("\ngot:\n%q\nwant:\n%q", got, wantre) } buf.Reset() l.Debug("test") if got := buf.Len(); got != 0 { t.Errorf("got buf.Len() = %d, want 0", got) } }
indenthandler
file
test
caa5c66e-1a37-4e75-83e2-2b2cc2329e9d
indent_handler.go
import ( "context" "fmt" "io" "log/slog" "runtime" "sync" "time" )
github.com/test//tmp/repos/example/slog-handler-guide/indenthandler2/indent_handler.go
//go:build go1.21 package indenthandler import ( "context" "fmt" "io" "log/slog" "runtime" "sync" "time" ) // !+IndentHandler type IndentHandler struct { opts Options goas []groupOrAttrs mu *sync.Mutex out io.Writer } //!-IndentHandler type Options struct { // Level reports the minimum level to log. // Levels with lower levels are discarded. // If nil, the Handler uses [slog.LevelInfo]. Level slog.Leveler } // !+gora // groupOrAttrs holds either a group name or a list of slog.Attrs. type groupOrAttrs struct { group string // group name if non-empty attrs []slog.Attr // attrs if non-empty } //!-gora func New(out io.Writer, opts *Options) *IndentHandler { h := &IndentHandler{out: out, mu: &sync.Mutex{}} if opts != nil { h.opts = *opts } if h.opts.Level == nil { h.opts.Level = slog.LevelInfo } return h } func (h *IndentHandler) Enabled(ctx context.Context, level slog.Level) bool { return level >= h.opts.Level.Level() } // !+withs func (h *IndentHandler) WithGroup(name string) slog.Handler { if name == "" { return h } return h.withGroupOrAttrs(groupOrAttrs{group: name}) } func (h *IndentHandler) WithAttrs(attrs []slog.Attr) slog.Handler { if len(attrs) == 0 { return h } return h.withGroupOrAttrs(groupOrAttrs{attrs: attrs}) } //!-withs // !+withgora func (h *IndentHandler) withGroupOrAttrs(goa groupOrAttrs) *IndentHandler { h2 := *h h2.goas = make([]groupOrAttrs, len(h.goas)+1) copy(h2.goas, h.goas) h2.goas[len(h2.goas)-1] = goa return &h2 } //!-withgora // !+handle func (h *IndentHandler) Handle(ctx context.Context, r slog.Record) error { buf := make([]byte, 0, 1024) if !r.Time.IsZero() { buf = h.appendAttr(buf, slog.Time(slog.TimeKey, r.Time), 0) } buf = h.appendAttr(buf, slog.Any(slog.LevelKey, r.Level), 0) if r.PC != 0 { fs := runtime.CallersFrames([]uintptr{r.PC}) f, _ := fs.Next() buf = h.appendAttr(buf, slog.String(slog.SourceKey, fmt.Sprintf("%s:%d", f.File, f.Line)), 0) } buf = h.appendAttr(buf, slog.String(slog.MessageKey, r.Message), 0) indentLevel := 0 // Handle state from WithGroup and WithAttrs. goas := h.goas if r.NumAttrs() == 0 { // If the record has no Attrs, remove groups at the end of the list; they are empty. for len(goas) > 0 && goas[len(goas)-1].group != "" { goas = goas[:len(goas)-1] } } for _, goa := range goas { if goa.group != "" { buf = fmt.Appendf(buf, "%*s%s:\n", indentLevel*4, "", goa.group) indentLevel++ } else { for _, a := range goa.attrs { buf = h.appendAttr(buf, a, indentLevel) } } } r.Attrs(func(a slog.Attr) bool { buf = h.appendAttr(buf, a, indentLevel) return true }) buf = append(buf, "---\n"...) h.mu.Lock() defer h.mu.Unlock() _, err := h.out.Write(buf) return err } //!-handle func (h *IndentHandler) appendAttr(buf []byte, a slog.Attr, indentLevel int) []byte { // Resolve the Attr's value before doing anything else. a.Value = a.Value.Resolve() // Ignore empty Attrs. if a.Equal(slog.Attr{}) { return buf } // Indent 4 spaces per level. buf = fmt.Appendf(buf, "%*s", indentLevel*4, "") switch a.Value.Kind() { case slog.KindString: // Quote string values, to make them easy to parse. buf = fmt.Appendf(buf, "%s: %q\n", a.Key, a.Value.String()) case slog.KindTime: // Write times in a standard way, without the monotonic time. buf = fmt.Appendf(buf, "%s: %s\n", a.Key, a.Value.Time().Format(time.RFC3339Nano)) case slog.KindGroup: attrs := a.Value.Group() // Ignore empty groups. if len(attrs) == 0 { return buf } // If the key is non-empty, write it out and indent the rest of the attrs. // Otherwise, inline the attrs. if a.Key != "" { buf = fmt.Appendf(buf, "%s:\n", a.Key) indentLevel++ } for _, ga := range attrs { buf = h.appendAttr(buf, ga, indentLevel) } default: buf = fmt.Appendf(buf, "%s: %s\n", a.Key, a.Value) } return buf }
package indenthandler
function
test
6549dad5-3e77-40dd-8107-ce07e96a46b0
New
['"io"', '"log/slog"', '"sync"']
['IndentHandler', 'Options']
github.com/test//tmp/repos/example/slog-handler-guide/indenthandler2/indent_handler.go
func New(out io.Writer, opts *Options) *IndentHandler { h := &IndentHandler{out: out, mu: &sync.Mutex{}} if opts != nil { h.opts = *opts } if h.opts.Level == nil { h.opts.Level = slog.LevelInfo } return h }
indenthandler
function
test
2d5e8a05-64bc-42a4-a155-261605077bf1
Enabled
['"context"', '"log/slog"']
['IndentHandler']
github.com/test//tmp/repos/example/slog-handler-guide/indenthandler2/indent_handler.go
func (h *IndentHandler) Enabled(ctx context.Context, level slog.Level) bool { return level >= h.opts.Level.Level() }
indenthandler
function
test
51c622ef-e418-4a64-bc1a-ad1e7ca7543b
WithGroup
['"log/slog"']
['IndentHandler', 'groupOrAttrs']
github.com/test//tmp/repos/example/slog-handler-guide/indenthandler2/indent_handler.go
func (h *IndentHandler) WithGroup(name string) slog.Handler { if name == "" { return h } return h.withGroupOrAttrs(groupOrAttrs{group: name}) }
indenthandler
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
6