Code Reviewer

Sends Go code to the model and gets back a JSON array of issues. Shows how to handle arrays and the empty case.

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
)

type Message struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

type Issue struct {
	Line        int    `json:"line"`
	Severity    string `json:"severity"`
	Description string `json:"description"`
}

func review(code string) []Issue {
	body, _ := json.Marshal(map[string]any{
		"model": "llama3.2",
		"messages": []Message{
			{Role: "system", Content: `Review the Go code for bugs and issues.
Return JSON: {"issues": [{"line": number, "severity": "high|medium|low", "description": "string"}]}
If no issues, return {"issues": []}. Return only the JSON.`},
			{Role: "user", Content: code},
		},
		"stream": false,
		"format": "json",
	})

	resp, err := http.Post("http://localhost:11434/api/chat", "application/json", bytes.NewReader(body))
	if err != nil {
		fmt.Println("Error:", err)
		return nil
	}
	defer resp.Body.Close()

	data, _ := io.ReadAll(resp.Body)
	var apiResp struct {
		Message struct {
			Content string `json:"content"`
		} `json:"message"`
	}
	json.Unmarshal(data, &apiResp)

	// Parse the wrapper object
	var wrapper struct {
		Issues []Issue `json:"issues"`
	}
	json.Unmarshal([]byte(apiResp.Message.Content), &wrapper)
	return wrapper.Issues
}

func main() {
	// Code with bugs
	buggy := `func divide(a, b int) int {
    return a / b
}

func main() {
    result := divide(10, 0)
    fmt.Println(result)
}`

	fmt.Println("=== Buggy code ===")
	issues := review(buggy)
	if len(issues) == 0 {
		fmt.Println("No issues found.")
	} else {
		for _, i := range issues {
			fmt.Printf("  Line %d [%s]: %s\n", i.Line, i.Severity, i.Description)
		}
	}
	// === Buggy code ===
	//   Line 5 [high]: Integer division by zero is undefined.

	// Clean code
	clean := `func add(a, b int) int {
    return a + b
}`

	fmt.Println("\n=== Clean code ===")
	issues = review(clean)
	if len(issues) == 0 {
		fmt.Println("No issues found.")
	} else {
		for _, i := range issues {
			fmt.Printf("  Line %d [%s]: %s\n", i.Line, i.Severity, i.Description)
		}
	}
	// Your results will vary. The model might find issues
	// you didn't expect, or miss ones you did.
	// That's the nature of LLM output.
}

💻 Run locally

Copy the code above and run it on your machine

© 2026 ByteLearn.dev. Free courses for developers. · Privacy