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
function
final HF test
8683fb98-c6d5-4a1a-96f9-63041faed94b
isTagged
['"log"', '"net/http"']
github.com/final HF 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
final HF test
d2c6f75c-ced5-4212-aa4a-f4ed26ac61a0
ServeHTTP
['"log"', '"net/http"']
['Server']
github.com/final HF 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
final HF test
1d4b0d1c-9147-4690-88ab-3ef33d6971c0
main_test.go
import ( "net/http" "net/http/httptest" "strings" "testing" "time" )
github.com/final HF 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
final HF test
6399438e-c626-4c55-96e9-2f29f3a00182
ServeHTTP
['"net/http"']
github.com/final HF test//tmp/repos/example/outyet/main_test.go
func (h *statusHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.WriteHeader(int(*h)) }
main
function
final HF test
a35086a2-0dd2-4bf5-a249-5146a2079c15
TestIsTagged
['"net/http"', '"net/http/httptest"', '"testing"']
github.com/final HF 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
final HF test
70dbf984-cf05-4b68-8db3-abc711eced9b
TestIntegration
['"net/http"', '"net/http/httptest"', '"strings"', '"testing"', '"time"']
github.com/final HF 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
final HF test
b159e09c-bc1a-4f49-981e-13c6cbe4c39a
json.go
import ( "encoding/json" "fmt" "mime" "net/http" )
github.com/final HF 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
final HF test
043509a5-db16-4a06-aa93-f0f103deb5f7
readRequestJSON
['"encoding/json"', '"fmt"', '"mime"', '"net/http"']
github.com/final HF 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
final HF test
4fe59c64-d59f-45c3-ac19-8bd34dbfe60c
renderJSON
['"encoding/json"', '"net/http"']
github.com/final HF 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
final HF test
7cf0fae0-a9ac-49f3-9405-0d4ee2ce7bb4
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/final HF 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
final HF test
43b14bea-8543-4ff6-80e3-143a06731020
main
['"cmp"', '"context"', '"log"', '"net/http"', '"os"', '"github.com/firebase/genkit/go/plugins/googleai"', '"github.com/firebase/genkit/go/plugins/weaviate"']
['ragServer']
github.com/final HF 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
final HF test
cd6031c1-78e7-4c1f-b66d-02da44e0ad47
addDocumentsHandler
['"fmt"', '"net/http"', '"github.com/firebase/genkit/go/ai"']
['ragServer']
github.com/final HF 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
final HF test
7dc13150-4f75-48d0-9f5d-d3196ed7c620
queryHandler
['"context"', '"fmt"', '"log"', '"net/http"', '"strings"', '"github.com/firebase/genkit/go/ai"', '"github.com/firebase/genkit/go/plugins/weaviate"']
['ragServer']
github.com/final HF 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
final HF test
6f647159-d287-4b98-be3d-22ba08a3f036
json.go
import ( "encoding/json" "fmt" "mime" "net/http" )
github.com/final HF 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
final HF test
1d5200d7-9d98-4383-bdae-cf37e9062a4e
readRequestJSON
['"encoding/json"', '"fmt"', '"mime"', '"net/http"']
github.com/final HF 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
final HF test
b46d619f-7e9c-40c1-a978-3df24a2cec19
renderJSON
['"encoding/json"', '"net/http"']
github.com/final HF 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
final HF test
733df1f2-185b-4caa-b6cd-8e2ebfbd2437
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/final HF 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
final HF test
003de45e-ebb5-4a26-8b75-51f2589b621e
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/final HF 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
final HF test
90fb6910-689b-42ed-aa9c-96a3adc192ea
addDocumentsHandler
['"net/http"', '"github.com/tmc/langchaingo/embeddings"', '"github.com/tmc/langchaingo/schema"', '"github.com/tmc/langchaingo/vectorstores/weaviate"']
['ragServer']
github.com/final HF 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
final HF test
dddd69a0-d482-41e9-bdc3-c24611e4735c
queryHandler
['"context"', '"fmt"', '"log"', '"net/http"', '"strings"', '"github.com/tmc/langchaingo/llms"']
['ragServer']
github.com/final HF 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
final HF test
0aeef777-7a21-4229-9441-2779ef1f595a
json.go
import ( "encoding/json" "fmt" "mime" "net/http" )
github.com/final HF 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
final HF test
326b405b-33d3-4f0a-a3aa-cf30779e453c
readRequestJSON
['"encoding/json"', '"fmt"', '"mime"', '"net/http"']
github.com/final HF 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
final HF test
e8e4bc06-851c-4b07-9729-674184c3fdea
renderJSON
['"encoding/json"', '"net/http"']
github.com/final HF 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
final HF test
c3c99832-3316-437e-978c-5d855c2ccc6d
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/final HF 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
final HF test
184a649a-7ff6-4381-8231-6a503d21cd5a
main
['"cmp"', '"context"', '"log"', '"net/http"', '"os"', '"github.com/google/generative-ai-go/genai"', '"google.golang.org/api/option"']
['ragServer']
github.com/final HF 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
final HF test
f7978ddc-a285-4566-a1f3-10cb26b898c0
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/final HF 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
final HF test
a8f29726-4b9a-4909-96b3-313df8529095
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/final HF 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
final HF test
0440682a-fadd-4177-bcbb-c34ac7b0461a
decodeGetResults
['"fmt"', '"github.com/weaviate/weaviate/entities/models"']
github.com/final HF 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
final HF test
54b3f235-dacd-4487-b8db-9b338b0b219a
weaviate.go
import ( "cmp" "context" "fmt" "os" "github.com/weaviate/weaviate-go-client/v4/weaviate" "github.com/weaviate/weaviate/entities/models" )
github.com/final HF 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
final HF test
fcaec229-b89a-4aa7-8686-faf5295c58a2
initWeaviate
['"cmp"', '"context"', '"fmt"', '"os"', '"github.com/weaviate/weaviate-go-client/v4/weaviate"', '"github.com/weaviate/weaviate/entities/models"']
github.com/final HF 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
final HF test
c9f9ff44-4e2b-4c84-bbd1-d63d9ea9d202
combinedWeaviateError
['"fmt"', '"github.com/weaviate/weaviate-go-client/v4/weaviate"', '"github.com/weaviate/weaviate/entities/models"']
github.com/final HF 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
final HF test
0fac4351-e7c0-4603-be2f-09d212888c49
indent_handler.go
import ( "context" "fmt" "io" "log/slog" "runtime" "sync" "time" )
github.com/final HF 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
final HF test
c3169ff3-110c-4736-8d4a-92394a9c6bae
New
['"io"', '"log/slog"', '"sync"']
['IndentHandler', 'Options']
github.com/final HF 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
final HF test
15c6869c-ba69-4e3a-b57c-747837553cc4
Enabled
['"context"', '"log/slog"']
['IndentHandler']
github.com/final HF 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
final HF test
a20b1f01-505c-4aa2-8165-904b8e1ad137
WithGroup
['"log/slog"']
['IndentHandler']
github.com/final HF 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
final HF test
0580a710-202d-478c-831d-7d8a95e4c489
WithAttrs
['"log/slog"']
['IndentHandler']
github.com/final HF 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
final HF test
b2794573-686e-4851-8951-d29b41eeca1d
Handle
['"context"', '"fmt"', '"log/slog"', '"runtime"']
['IndentHandler']
github.com/final HF 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
final HF test
962079b7-c94b-46b6-982b-a5cf4a0aa795
appendAttr
['"fmt"', '"log/slog"', '"time"']
['IndentHandler']
github.com/final HF 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
final HF test
d8202f65-0a56-4e44-b02f-b2dcc7dbf111
indent_handler_test.go
import ( "bytes" "regexp" "testing" "log/slog" )
github.com/final HF 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
final HF test
e4c7cd1e-2e6d-4ad2-8d5c-2c2a8cece695
Test
['"bytes"', '"regexp"', '"testing"', '"log/slog"']
github.com/final HF 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
final HF test
37fa592a-36c6-4aae-a440-a836f5270850
indent_handler.go
import ( "context" "fmt" "io" "log/slog" "runtime" "sync" "time" )
github.com/final HF 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
final HF test
30296a8e-c37b-4d13-b98c-7b5888e11981
New
['"io"', '"log/slog"', '"sync"']
['IndentHandler', 'Options']
github.com/final HF 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
final HF test
4648b6ee-3bff-4bec-ac0e-60108cef9e9a
Enabled
['"context"', '"log/slog"']
['IndentHandler']
github.com/final HF 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
final HF test
b4593950-e883-438c-9b8e-cad8ea9f2179
WithGroup
['"log/slog"']
['IndentHandler', 'groupOrAttrs']
github.com/final HF 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
function
final HF test
b8b79e27-d9b4-436b-b0db-d50b9c4cf270
WithAttrs
['"log/slog"']
['IndentHandler', 'groupOrAttrs']
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler2/indent_handler.go
func (h *IndentHandler) WithAttrs(attrs []slog.Attr) slog.Handler { if len(attrs) == 0 { return h } return h.withGroupOrAttrs(groupOrAttrs{attrs: attrs}) }
indenthandler
function
final HF test
19c582b8-5a53-45fe-9d4d-d5bb139126e2
withGroupOrAttrs
['IndentHandler', 'groupOrAttrs']
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler2/indent_handler.go
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 }
indenthandler
function
final HF test
7b13703a-acf6-4ded-b145-76cded494dc4
Handle
['"context"', '"fmt"', '"log/slog"', '"runtime"']
['IndentHandler']
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler2/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 // 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 }
indenthandler
function
final HF test
37647541-7779-490f-aba6-16c8018393d5
appendAttr
['"fmt"', '"log/slog"', '"time"']
['IndentHandler']
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler2/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
final HF test
b0de6400-eed1-4237-af75-d8440d92ba33
indent_handler_test.go
import ( "bufio" "bytes" "fmt" "reflect" "regexp" "strconv" "strings" "testing" "unicode" "log/slog" "testing/slogtest" )
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler2/indent_handler_test.go
//go:build go1.21 package indenthandler import ( "bufio" "bytes" "fmt" "reflect" "regexp" "strconv" "strings" "testing" "unicode" "log/slog" "testing/slogtest" ) func TestSlogtest(t *testing.T) { var buf bytes.Buffer err := slogtest.TestHandler(New(&buf, nil), func() []map[string]any { return parseLogEntries(buf.String()) }) if err != nil { t.Error(err) } } 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) } } func parseLogEntries(s string) []map[string]any { var ms []map[string]any scan := bufio.NewScanner(strings.NewReader(s)) for scan.Scan() { m := parseGroup(scan) ms = append(ms, m) } if scan.Err() != nil { panic(scan.Err()) } return ms } func parseGroup(scan *bufio.Scanner) map[string]any { m := map[string]any{} groupIndent := -1 for { line := scan.Text() if line == "---" { // end of entry break } k, v, found := strings.Cut(line, ":") if !found { panic(fmt.Sprintf("no ':' in line %q", line)) } indent := strings.IndexFunc(k, func(r rune) bool { return !unicode.IsSpace(r) }) if indent < 0 { panic("blank line") } if groupIndent < 0 { // First line in group; remember the indent. groupIndent = indent } else if indent < groupIndent { // End of group break } else if indent > groupIndent { panic(fmt.Sprintf("indent increased on line %q", line)) } key := strings.TrimSpace(k) if v == "" { // Just a key: start of a group. if !scan.Scan() { panic("empty group") } m[key] = parseGroup(scan) } else { v = strings.TrimSpace(v) if len(v) > 0 && v[0] == '"' { var err error v, err = strconv.Unquote(v) if err != nil { panic(err) } } m[key] = v if !scan.Scan() { break } } } return m } func TestParseLogEntries(t *testing.T) { in := ` a: 1 b: 2 c: 3 g: h: 4 i: 5 d: 6 --- e: 7 --- ` want := []map[string]any{ { "a": "1", "b": "2", "c": "3", "g": map[string]any{ "h": "4", "i": "5", }, "d": "6", }, { "e": "7", }, } got := parseLogEntries(in[1:]) if !reflect.DeepEqual(got, want) { t.Errorf("\ngot:\n%v\nwant:\n%v", got, want) } }
package indenthandler
function
final HF test
22234303-350a-49d6-95fe-968cd7069d57
TestSlogtest
['"bytes"', '"testing"', '"testing/slogtest"']
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler2/indent_handler_test.go
func TestSlogtest(t *testing.T) { var buf bytes.Buffer err := slogtest.TestHandler(New(&buf, nil), func() []map[string]any { return parseLogEntries(buf.String()) }) if err != nil { t.Error(err) } }
indenthandler
function
final HF test
972de21a-cf7c-4ab5-897d-99d0e3ebe3fe
Test
['"bytes"', '"regexp"', '"testing"', '"log/slog"']
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler2/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
function
final HF test
abe6a775-1702-418e-adac-a0e294d3ad44
parseLogEntries
['"bufio"', '"strings"']
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler2/indent_handler_test.go
func parseLogEntries(s string) []map[string]any { var ms []map[string]any scan := bufio.NewScanner(strings.NewReader(s)) for scan.Scan() { m := parseGroup(scan) ms = append(ms, m) } if scan.Err() != nil { panic(scan.Err()) } return ms }
indenthandler
function
final HF test
72b14e96-f7a3-46c6-ba98-252407284296
parseGroup
['"bufio"', '"fmt"', '"strconv"', '"strings"', '"unicode"']
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler2/indent_handler_test.go
func parseGroup(scan *bufio.Scanner) map[string]any { m := map[string]any{} groupIndent := -1 for { line := scan.Text() if line == "---" { // end of entry break } k, v, found := strings.Cut(line, ":") if !found { panic(fmt.Sprintf("no ':' in line %q", line)) } indent := strings.IndexFunc(k, func(r rune) bool { return !unicode.IsSpace(r) }) if indent < 0 { panic("blank line") } if groupIndent < 0 { // First line in group; remember the indent. groupIndent = indent } else if indent < groupIndent { // End of group break } else if indent > groupIndent { panic(fmt.Sprintf("indent increased on line %q", line)) } key := strings.TrimSpace(k) if v == "" { // Just a key: start of a group. if !scan.Scan() { panic("empty group") } m[key] = parseGroup(scan) } else { v = strings.TrimSpace(v) if len(v) > 0 && v[0] == '"' { var err error v, err = strconv.Unquote(v) if err != nil { panic(err) } } m[key] = v if !scan.Scan() { break } } } return m }
indenthandler
function
final HF test
28138c51-ed44-4c0f-9073-04149384be51
TestParseLogEntries
['"reflect"', '"testing"']
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler2/indent_handler_test.go
func TestParseLogEntries(t *testing.T) { in := ` a: 1 b: 2 c: 3 g: h: 4 i: 5 d: 6 --- e: 7 --- ` want := []map[string]any{ { "a": "1", "b": "2", "c": "3", "g": map[string]any{ "h": "4", "i": "5", }, "d": "6", }, { "e": "7", }, } got := parseLogEntries(in[1:]) if !reflect.DeepEqual(got, want) { t.Errorf("\ngot:\n%v\nwant:\n%v", got, want) } }
indenthandler
file
final HF test
5d03854b-9eca-4d03-8cfb-58d544fbd926
indent_handler.go
import ( "context" "fmt" "io" "log/slog" "runtime" "slices" "sync" "time" )
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler3/indent_handler.go
//go:build go1.21 package indenthandler import ( "context" "fmt" "io" "log/slog" "runtime" "slices" "sync" "time" ) // !+IndentHandler type IndentHandler struct { opts Options preformatted []byte // data from WithGroup and WithAttrs unopenedGroups []string // groups from WithGroup that haven't been opened indentLevel int // same as number of opened groups so far 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 } 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() } // !+WithGroup func (h *IndentHandler) WithGroup(name string) slog.Handler { if name == "" { return h } h2 := *h // Add an unopened group to h2 without modifying h. h2.unopenedGroups = make([]string, len(h.unopenedGroups)+1) copy(h2.unopenedGroups, h.unopenedGroups) h2.unopenedGroups[len(h2.unopenedGroups)-1] = name return &h2 } //!-WithGroup // !+WithAttrs func (h *IndentHandler) WithAttrs(attrs []slog.Attr) slog.Handler { if len(attrs) == 0 { return h } h2 := *h // Force an append to copy the underlying array. pre := slices.Clip(h.preformatted) // Add all groups from WithGroup that haven't already been added. h2.preformatted = h2.appendUnopenedGroups(pre, h2.indentLevel) // Each of those groups increased the indent level by 1. h2.indentLevel += len(h2.unopenedGroups) // Now all groups have been opened. h2.unopenedGroups = nil // Pre-format the attributes. for _, a := range attrs { h2.preformatted = h2.appendAttr(h2.preformatted, a, h2.indentLevel) } return &h2 } func (h *IndentHandler) appendUnopenedGroups(buf []byte, indentLevel int) []byte { for _, g := range h.unopenedGroups { buf = fmt.Appendf(buf, "%*s%s:\n", indentLevel*4, "", g) indentLevel++ } return buf } //!-WithAttrs // !+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) // Insert preformatted attributes just after built-in ones. buf = append(buf, h.preformatted...) if r.NumAttrs() > 0 { buf = h.appendUnopenedGroups(buf, h.indentLevel) r.Attrs(func(a slog.Attr) bool { buf = h.appendAttr(buf, a, h.indentLevel+len(h.unopenedGroups)) 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
final HF test
d8987d99-511b-4e83-8c5c-be53ac19e30c
New
['"io"', '"log/slog"', '"sync"']
['IndentHandler', 'Options']
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler3/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
final HF test
fe4a74d8-79a1-487e-9df2-28450312a10d
Enabled
['"context"', '"log/slog"']
['IndentHandler']
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler3/indent_handler.go
func (h *IndentHandler) Enabled(ctx context.Context, level slog.Level) bool { return level >= h.opts.Level.Level() }
indenthandler
function
final HF test
71ea3541-200e-4743-97a4-2472946a1d94
WithGroup
['"log/slog"']
['IndentHandler']
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler3/indent_handler.go
func (h *IndentHandler) WithGroup(name string) slog.Handler { if name == "" { return h } h2 := *h // Add an unopened group to h2 without modifying h. h2.unopenedGroups = make([]string, len(h.unopenedGroups)+1) copy(h2.unopenedGroups, h.unopenedGroups) h2.unopenedGroups[len(h2.unopenedGroups)-1] = name return &h2 }
indenthandler
function
final HF test
14d364da-0ee5-4c5b-9ad0-62683cd6c9c9
WithAttrs
['"log/slog"', '"slices"']
['IndentHandler']
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler3/indent_handler.go
func (h *IndentHandler) WithAttrs(attrs []slog.Attr) slog.Handler { if len(attrs) == 0 { return h } h2 := *h // Force an append to copy the underlying array. pre := slices.Clip(h.preformatted) // Add all groups from WithGroup that haven't already been added. h2.preformatted = h2.appendUnopenedGroups(pre, h2.indentLevel) // Each of those groups increased the indent level by 1. h2.indentLevel += len(h2.unopenedGroups) // Now all groups have been opened. h2.unopenedGroups = nil // Pre-format the attributes. for _, a := range attrs { h2.preformatted = h2.appendAttr(h2.preformatted, a, h2.indentLevel) } return &h2 }
indenthandler
function
final HF test
87bfa51c-9d0a-4c87-ab74-36d1e2ba5623
appendUnopenedGroups
['"fmt"']
['IndentHandler']
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler3/indent_handler.go
func (h *IndentHandler) appendUnopenedGroups(buf []byte, indentLevel int) []byte { for _, g := range h.unopenedGroups { buf = fmt.Appendf(buf, "%*s%s:\n", indentLevel*4, "", g) indentLevel++ } return buf }
indenthandler
function
final HF test
092cfe45-64e3-4055-8100-1319deb3fed2
Handle
['"context"', '"fmt"', '"log/slog"', '"runtime"']
['IndentHandler']
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler3/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) // Insert preformatted attributes just after built-in ones. buf = append(buf, h.preformatted...) if r.NumAttrs() > 0 { buf = h.appendUnopenedGroups(buf, h.indentLevel) r.Attrs(func(a slog.Attr) bool { buf = h.appendAttr(buf, a, h.indentLevel+len(h.unopenedGroups)) return true }) } buf = append(buf, "---\n"...) h.mu.Lock() defer h.mu.Unlock() _, err := h.out.Write(buf) return err }
indenthandler
function
final HF test
b3392954-97e1-40d0-a136-2ec22e3108af
appendAttr
['"fmt"', '"log/slog"', '"time"']
['IndentHandler']
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler3/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
final HF test
2f83670d-fb86-4278-b3a8-7ad75353ed87
indent_handler_test.go
import ( "bytes" "log/slog" "reflect" "regexp" "testing" "testing/slogtest" "gopkg.in/yaml.v3" )
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler3/indent_handler_test.go
//go:build go1.21 package indenthandler import ( "bytes" "log/slog" "reflect" "regexp" "testing" "testing/slogtest" "gopkg.in/yaml.v3" ) // !+TestSlogtest func TestSlogtest(t *testing.T) { var buf bytes.Buffer err := slogtest.TestHandler(New(&buf, nil), func() []map[string]any { return parseLogEntries(t, buf.Bytes()) }) if err != nil { t.Error(err) } } // !-TestSlogtest 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) } } // !+parseLogEntries func parseLogEntries(t *testing.T, data []byte) []map[string]any { entries := bytes.Split(data, []byte("---\n")) entries = entries[:len(entries)-1] // last one is empty var ms []map[string]any for _, e := range entries { var m map[string]any if err := yaml.Unmarshal([]byte(e), &m); err != nil { t.Fatal(err) } ms = append(ms, m) } return ms } // !-parseLogEntries func TestParseLogEntries(t *testing.T) { in := ` a: 1 b: 2 c: 3 g: h: 4 i: five d: 6 --- e: 7 --- ` want := []map[string]any{ { "a": 1, "b": 2, "c": 3, "g": map[string]any{ "h": 4, "i": "five", }, "d": 6, }, { "e": 7, }, } got := parseLogEntries(t, []byte(in[1:])) if !reflect.DeepEqual(got, want) { t.Errorf("\ngot:\n%v\nwant:\n%v", got, want) } }
package indenthandler
function
final HF test
19f6d5f5-9108-43af-902d-ef3880238f4c
TestSlogtest
['"bytes"', '"testing"', '"testing/slogtest"']
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler3/indent_handler_test.go
func TestSlogtest(t *testing.T) { var buf bytes.Buffer err := slogtest.TestHandler(New(&buf, nil), func() []map[string]any { return parseLogEntries(t, buf.Bytes()) }) if err != nil { t.Error(err) } }
indenthandler
function
final HF test
a1d0c814-98b1-4171-986f-851a39d64ae7
Test
['"bytes"', '"log/slog"', '"regexp"', '"testing"']
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler3/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
function
final HF test
7b2495ce-43e8-4be8-b7b1-7abcb0b54c9f
parseLogEntries
['"bytes"', '"testing"']
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler3/indent_handler_test.go
func parseLogEntries(t *testing.T, data []byte) []map[string]any { entries := bytes.Split(data, []byte("---\n")) entries = entries[:len(entries)-1] // last one is empty var ms []map[string]any for _, e := range entries { var m map[string]any if err := yaml.Unmarshal([]byte(e), &m); err != nil { t.Fatal(err) } ms = append(ms, m) } return ms }
indenthandler
function
final HF test
f1212ef6-e7c4-4596-90a7-16866ab6e292
TestParseLogEntries
['"reflect"', '"testing"']
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler3/indent_handler_test.go
func TestParseLogEntries(t *testing.T) { in := ` a: 1 b: 2 c: 3 g: h: 4 i: five d: 6 --- e: 7 --- ` want := []map[string]any{ { "a": 1, "b": 2, "c": 3, "g": map[string]any{ "h": 4, "i": "five", }, "d": 6, }, { "e": 7, }, } got := parseLogEntries(t, []byte(in[1:])) if !reflect.DeepEqual(got, want) { t.Errorf("\ngot:\n%v\nwant:\n%v", got, want) } }
indenthandler
file
final HF test
d0cc46d9-7877-433f-a444-b35d6a6e3ad6
indent_handler.go
import ( "context" "fmt" "io" "log/slog" "runtime" "slices" "strconv" "sync" "time" )
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler4/indent_handler.go
//go:build go1.21 package indenthandler import ( "context" "fmt" "io" "log/slog" "runtime" "slices" "strconv" "sync" "time" ) // !+IndentHandler type IndentHandler struct { opts Options preformatted []byte // data from WithGroup and WithAttrs unopenedGroups []string // groups from WithGroup that haven't been opened indentLevel int // same as number of opened groups so far 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 } 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() } // !+WithGroup func (h *IndentHandler) WithGroup(name string) slog.Handler { if name == "" { return h } h2 := *h // Add an unopened group to h2 without modifying h. h2.unopenedGroups = make([]string, len(h.unopenedGroups)+1) copy(h2.unopenedGroups, h.unopenedGroups) h2.unopenedGroups[len(h2.unopenedGroups)-1] = name return &h2 } //!-WithGroup // !+WithAttrs func (h *IndentHandler) WithAttrs(attrs []slog.Attr) slog.Handler { if len(attrs) == 0 { return h } h2 := *h // Force an append to copy the underlying array. pre := slices.Clip(h.preformatted) // Add all groups from WithGroup that haven't already been added. h2.preformatted = h2.appendUnopenedGroups(pre, h2.indentLevel) // Each of those groups increased the indent level by 1. h2.indentLevel += len(h2.unopenedGroups) // Now all groups have been opened. h2.unopenedGroups = nil // Pre-format the attributes. for _, a := range attrs { h2.preformatted = h2.appendAttr(h2.preformatted, a, h2.indentLevel) } return &h2 } func (h *IndentHandler) appendUnopenedGroups(buf []byte, indentLevel int) []byte { for _, g := range h.unopenedGroups { buf = fmt.Appendf(buf, "%*s%s:\n", indentLevel*4, "", g) indentLevel++ } return buf } //!-WithAttrs // !+Handle func (h *IndentHandler) Handle(ctx context.Context, r slog.Record) error { bufp := allocBuf() buf := *bufp defer func() { *bufp = buf freeBuf(bufp) }() 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() // Optimize to minimize allocation. srcbufp := allocBuf() defer freeBuf(srcbufp) *srcbufp = append(*srcbufp, f.File...) *srcbufp = append(*srcbufp, ':') *srcbufp = strconv.AppendInt(*srcbufp, int64(f.Line), 10) buf = h.appendAttr(buf, slog.String(slog.SourceKey, string(*srcbufp)), 0) } buf = h.appendAttr(buf, slog.String(slog.MessageKey, r.Message), 0) // Insert preformatted attributes just after built-in ones. buf = append(buf, h.preformatted...) if r.NumAttrs() > 0 { buf = h.appendUnopenedGroups(buf, h.indentLevel) r.Attrs(func(a slog.Attr) bool { buf = h.appendAttr(buf, a, h.indentLevel+len(h.unopenedGroups)) 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 = append(buf, a.Key...) buf = append(buf, ": "...) buf = strconv.AppendQuote(buf, a.Value.String()) buf = append(buf, '\n') case slog.KindTime: // Write times in a standard way, without the monotonic time. buf = append(buf, a.Key...) buf = append(buf, ": "...) buf = a.Value.Time().AppendFormat(buf, time.RFC3339Nano) buf = append(buf, '\n') 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 = append(buf, a.Key...) buf = append(buf, ": "...) buf = append(buf, a.Value.String()...) buf = append(buf, '\n') } return buf } // !+pool var bufPool = sync.Pool{ New: func() any { b := make([]byte, 0, 1024) return &b }, } func allocBuf() *[]byte { return bufPool.Get().(*[]byte) } func freeBuf(b *[]byte) { // To reduce peak allocation, return only smaller buffers to the pool. const maxBufferSize = 16 << 10 if cap(*b) <= maxBufferSize { *b = (*b)[:0] bufPool.Put(b) } } //!-pool
package indenthandler
function
final HF test
0db91957-54ea-4c55-bede-8698b934a246
New
['"io"', '"log/slog"', '"sync"']
['IndentHandler', 'Options']
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler4/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
final HF test
d846e883-1a24-48cc-bc73-1ae607b04cae
Enabled
['"context"', '"log/slog"']
['IndentHandler']
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler4/indent_handler.go
func (h *IndentHandler) Enabled(ctx context.Context, level slog.Level) bool { return level >= h.opts.Level.Level() }
indenthandler
function
final HF test
a75cf018-6028-4dec-9c34-fae1f1bbabed
WithGroup
['"log/slog"']
['IndentHandler']
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler4/indent_handler.go
func (h *IndentHandler) WithGroup(name string) slog.Handler { if name == "" { return h } h2 := *h // Add an unopened group to h2 without modifying h. h2.unopenedGroups = make([]string, len(h.unopenedGroups)+1) copy(h2.unopenedGroups, h.unopenedGroups) h2.unopenedGroups[len(h2.unopenedGroups)-1] = name return &h2 }
indenthandler
function
final HF test
7ce319d1-d205-4048-8c38-403489e650b0
WithAttrs
['"log/slog"', '"slices"']
['IndentHandler']
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler4/indent_handler.go
func (h *IndentHandler) WithAttrs(attrs []slog.Attr) slog.Handler { if len(attrs) == 0 { return h } h2 := *h // Force an append to copy the underlying array. pre := slices.Clip(h.preformatted) // Add all groups from WithGroup that haven't already been added. h2.preformatted = h2.appendUnopenedGroups(pre, h2.indentLevel) // Each of those groups increased the indent level by 1. h2.indentLevel += len(h2.unopenedGroups) // Now all groups have been opened. h2.unopenedGroups = nil // Pre-format the attributes. for _, a := range attrs { h2.preformatted = h2.appendAttr(h2.preformatted, a, h2.indentLevel) } return &h2 }
indenthandler
function
final HF test
0d12393b-5e2a-4b4f-aa43-925faea28ba7
appendUnopenedGroups
['"fmt"']
['IndentHandler']
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler4/indent_handler.go
func (h *IndentHandler) appendUnopenedGroups(buf []byte, indentLevel int) []byte { for _, g := range h.unopenedGroups { buf = fmt.Appendf(buf, "%*s%s:\n", indentLevel*4, "", g) indentLevel++ } return buf }
indenthandler
function
final HF test
efed7757-fa96-41b6-9b53-c851a5046d62
Handle
['"context"', '"log/slog"', '"runtime"', '"strconv"']
['IndentHandler']
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler4/indent_handler.go
func (h *IndentHandler) Handle(ctx context.Context, r slog.Record) error { bufp := allocBuf() buf := *bufp defer func() { *bufp = buf freeBuf(bufp) }() 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() // Optimize to minimize allocation. srcbufp := allocBuf() defer freeBuf(srcbufp) *srcbufp = append(*srcbufp, f.File...) *srcbufp = append(*srcbufp, ':') *srcbufp = strconv.AppendInt(*srcbufp, int64(f.Line), 10) buf = h.appendAttr(buf, slog.String(slog.SourceKey, string(*srcbufp)), 0) } buf = h.appendAttr(buf, slog.String(slog.MessageKey, r.Message), 0) // Insert preformatted attributes just after built-in ones. buf = append(buf, h.preformatted...) if r.NumAttrs() > 0 { buf = h.appendUnopenedGroups(buf, h.indentLevel) r.Attrs(func(a slog.Attr) bool { buf = h.appendAttr(buf, a, h.indentLevel+len(h.unopenedGroups)) return true }) } buf = append(buf, "---\n"...) h.mu.Lock() defer h.mu.Unlock() _, err := h.out.Write(buf) return err }
indenthandler
function
final HF test
af1596fe-5852-4c7d-a678-d2bdeaa9bd78
appendAttr
['"fmt"', '"log/slog"', '"strconv"', '"time"']
['IndentHandler']
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler4/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 = append(buf, a.Key...) buf = append(buf, ": "...) buf = strconv.AppendQuote(buf, a.Value.String()) buf = append(buf, '\n') case slog.KindTime: // Write times in a standard way, without the monotonic time. buf = append(buf, a.Key...) buf = append(buf, ": "...) buf = a.Value.Time().AppendFormat(buf, time.RFC3339Nano) buf = append(buf, '\n') 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 = append(buf, a.Key...) buf = append(buf, ": "...) buf = append(buf, a.Value.String()...) buf = append(buf, '\n') } return buf }
indenthandler
function
final HF test
9b41ed77-f3e0-48cf-aba5-9d4f615989f0
allocBuf
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler4/indent_handler.go
func allocBuf() *[]byte { return bufPool.Get().(*[]byte) }
indenthandler
function
final HF test
f23ea677-eeee-4903-9d2f-610b01b1743f
freeBuf
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler4/indent_handler.go
func freeBuf(b *[]byte) { // To reduce peak allocation, return only smaller buffers to the pool. const maxBufferSize = 16 << 10 if cap(*b) <= maxBufferSize { *b = (*b)[:0] bufPool.Put(b) } }
indenthandler
file
final HF test
10bdf0a4-aaf1-42e9-a44e-7567ad200bf4
indent_handler_norace_test.go
import ( "fmt" "io" "log/slog" "strconv" "testing" )
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler4/indent_handler_norace_test.go
//go:build go1.21 && !race package indenthandler import ( "fmt" "io" "log/slog" "strconv" "testing" ) func TestAlloc(t *testing.T) { a := slog.String("key", "value") t.Run("Appendf", func(t *testing.T) { buf := make([]byte, 0, 100) g := testing.AllocsPerRun(2, func() { buf = fmt.Appendf(buf, "%s: %q\n", a.Key, a.Value.String()) }) if g, w := int(g), 2; g != w { t.Errorf("got %d, want %d", g, w) } }) t.Run("appends", func(t *testing.T) { buf := make([]byte, 0, 100) g := testing.AllocsPerRun(2, func() { buf = append(buf, a.Key...) buf = append(buf, ": "...) buf = strconv.AppendQuote(buf, a.Value.String()) buf = append(buf, '\n') }) if g, w := int(g), 0; g != w { t.Errorf("got %d, want %d", g, w) } }) t.Run("Handle", func(t *testing.T) { l := slog.New(New(io.Discard, nil)) got := testing.AllocsPerRun(10, func() { l.LogAttrs(nil, slog.LevelInfo, "hello", slog.String("a", "1")) }) if g, w := int(got), 6; g > w { t.Errorf("got %d, want at most %d", g, w) } }) }
package indenthandler
function
final HF test
2ca9b1f0-2a2d-4363-821f-a9ca95d4a5f6
TestAlloc
['"fmt"', '"io"', '"log/slog"', '"strconv"', '"testing"']
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler4/indent_handler_norace_test.go
func TestAlloc(t *testing.T) { a := slog.String("key", "value") t.Run("Appendf", func(t *testing.T) { buf := make([]byte, 0, 100) g := testing.AllocsPerRun(2, func() { buf = fmt.Appendf(buf, "%s: %q\n", a.Key, a.Value.String()) }) if g, w := int(g), 2; g != w { t.Errorf("got %d, want %d", g, w) } }) t.Run("appends", func(t *testing.T) { buf := make([]byte, 0, 100) g := testing.AllocsPerRun(2, func() { buf = append(buf, a.Key...) buf = append(buf, ": "...) buf = strconv.AppendQuote(buf, a.Value.String()) buf = append(buf, '\n') }) if g, w := int(g), 0; g != w { t.Errorf("got %d, want %d", g, w) } }) t.Run("Handle", func(t *testing.T) { l := slog.New(New(io.Discard, nil)) got := testing.AllocsPerRun(10, func() { l.LogAttrs(nil, slog.LevelInfo, "hello", slog.String("a", "1")) }) if g, w := int(got), 6; g > w { t.Errorf("got %d, want at most %d", g, w) } }) }
indenthandler
file
final HF test
02a81711-d92e-4496-ab99-5f3d59f7f9fe
indent_handler_test.go
import ( "bytes" "log/slog" "reflect" "regexp" "testing" "testing/slogtest" "gopkg.in/yaml.v3" )
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler4/indent_handler_test.go
//go:build go1.21 package indenthandler import ( "bytes" "log/slog" "reflect" "regexp" "testing" "testing/slogtest" "gopkg.in/yaml.v3" ) // !+TestSlogtest func TestSlogtest(t *testing.T) { var buf bytes.Buffer err := slogtest.TestHandler(New(&buf, nil), func() []map[string]any { return parseLogEntries(t, buf.Bytes()) }) if err != nil { t.Error(err) } } // !-TestSlogtest 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) } } // !+parseLogEntries func parseLogEntries(t *testing.T, data []byte) []map[string]any { entries := bytes.Split(data, []byte("---\n")) entries = entries[:len(entries)-1] // last one is empty var ms []map[string]any for _, e := range entries { var m map[string]any if err := yaml.Unmarshal([]byte(e), &m); err != nil { t.Fatal(err) } ms = append(ms, m) } return ms } // !-parseLogEntries func TestParseLogEntries(t *testing.T) { in := ` a: 1 b: 2 c: 3 g: h: 4 i: five d: 6 --- e: 7 --- ` want := []map[string]any{ { "a": 1, "b": 2, "c": 3, "g": map[string]any{ "h": 4, "i": "five", }, "d": 6, }, { "e": 7, }, } got := parseLogEntries(t, []byte(in[1:])) if !reflect.DeepEqual(got, want) { t.Errorf("\ngot:\n%v\nwant:\n%v", got, want) } }
package indenthandler
function
final HF test
c67014b6-00f0-44a0-8c52-89af0bb83f93
TestSlogtest
['"bytes"', '"testing"', '"testing/slogtest"']
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler4/indent_handler_test.go
func TestSlogtest(t *testing.T) { var buf bytes.Buffer err := slogtest.TestHandler(New(&buf, nil), func() []map[string]any { return parseLogEntries(t, buf.Bytes()) }) if err != nil { t.Error(err) } }
indenthandler
function
final HF test
6268d7b9-13c4-46ce-a268-b33b9280f388
Test
['"bytes"', '"log/slog"', '"regexp"', '"testing"']
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler4/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
function
final HF test
75769bfd-495f-4617-adf6-6e0e06594f57
parseLogEntries
['"bytes"', '"testing"']
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler4/indent_handler_test.go
func parseLogEntries(t *testing.T, data []byte) []map[string]any { entries := bytes.Split(data, []byte("---\n")) entries = entries[:len(entries)-1] // last one is empty var ms []map[string]any for _, e := range entries { var m map[string]any if err := yaml.Unmarshal([]byte(e), &m); err != nil { t.Fatal(err) } ms = append(ms, m) } return ms }
indenthandler
function
final HF test
8c7a082e-8718-4e10-a75a-67027d125164
TestParseLogEntries
['"reflect"', '"testing"']
github.com/final HF test//tmp/repos/example/slog-handler-guide/indenthandler4/indent_handler_test.go
func TestParseLogEntries(t *testing.T) { in := ` a: 1 b: 2 c: 3 g: h: 4 i: five d: 6 --- e: 7 --- ` want := []map[string]any{ { "a": 1, "b": 2, "c": 3, "g": map[string]any{ "h": 4, "i": "five", }, "d": 6, }, { "e": 7, }, } got := parseLogEntries(t, []byte(in[1:])) if !reflect.DeepEqual(got, want) { t.Errorf("\ngot:\n%v\nwant:\n%v", got, want) } }
indenthandler
file
final HF test
cfe6b168-591d-4410-b667-5a1bf1c1d710
main.go
import ( "html/template" "log" "net/http" "strings" )
github.com/final HF test//tmp/repos/example/template/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. // Template is a trivial web server that uses the text/template (and // html/template) package's "block" feature to implement a kind of template // inheritance. // // It should be executed from the directory in which the source resides, // as it will look for its template files in the current directory. package main import ( "html/template" "log" "net/http" "strings" ) func main() { http.HandleFunc("/", indexHandler) http.HandleFunc("/image/", imageHandler) log.Fatal(http.ListenAndServe("localhost:8080", nil)) } // indexTemplate is the main site template. // The default template includes two template blocks ("sidebar" and "content") // that may be replaced in templates derived from this one. var indexTemplate = template.Must(template.ParseFiles("index.tmpl")) // Index is a data structure used to populate an indexTemplate. type Index struct { Title string Body string Links []Link } type Link struct { URL, Title string } // indexHandler is an HTTP handler that serves the index page. func indexHandler(w http.ResponseWriter, r *http.Request) { data := &Index{ Title: "Image gallery", Body: "Welcome to the image gallery.", } for name, img := range images { data.Links = append(data.Links, Link{ URL: "/image/" + name, Title: img.Title, }) } if err := indexTemplate.Execute(w, data); err != nil { log.Println(err) } } // imageTemplate is a clone of indexTemplate that provides // alternate "sidebar" and "content" templates. var imageTemplate = template.Must(template.Must(indexTemplate.Clone()).ParseFiles("image.tmpl")) // Image is a data structure used to populate an imageTemplate. type Image struct { Title string URL string } // imageHandler is an HTTP handler that serves the image pages. func imageHandler(w http.ResponseWriter, r *http.Request) { data, ok := images[strings.TrimPrefix(r.URL.Path, "/image/")] if !ok { http.NotFound(w, r) return } if err := imageTemplate.Execute(w, data); err != nil { log.Println(err) } } // images specifies the site content: a collection of images. var images = map[string]*Image{ "go": {"The Go Gopher", "https://golang.org/doc/gopher/frontpage.png"}, "google": {"The Google Logo", "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png"}, }
package main
function
final HF test
d6de7321-e166-42d9-bcf9-8e4f2ca64f74
main
['"log"', '"net/http"']
github.com/final HF test//tmp/repos/example/template/main.go
func main() { http.HandleFunc("/", indexHandler) http.HandleFunc("/image/", imageHandler) log.Fatal(http.ListenAndServe("localhost:8080", nil)) }
main
function
final HF test
398cd1b5-e83e-46b7-9fa2-a078fbe6207f
indexHandler
['"log"', '"net/http"']
['Index', 'Link', 'Image']
github.com/final HF test//tmp/repos/example/template/main.go
func indexHandler(w http.ResponseWriter, r *http.Request) { data := &Index{ Title: "Image gallery", Body: "Welcome to the image gallery.", } for name, img := range images { data.Links = append(data.Links, Link{ URL: "/image/" + name, Title: img.Title, }) } if err := indexTemplate.Execute(w, data); err != nil { log.Println(err) } }
main
function
final HF test
22ef6dde-34ab-418b-abee-9e4459efe0f5
imageHandler
['"log"', '"net/http"', '"strings"']
github.com/final HF test//tmp/repos/example/template/main.go
func imageHandler(w http.ResponseWriter, r *http.Request) { data, ok := images[strings.TrimPrefix(r.URL.Path, "/image/")] if !ok { http.NotFound(w, r) return } if err := imageTemplate.Execute(w, data); err != nil { log.Println(err) } }
main