Sentiment Analyzer
Sends a message to Ollama with JSON mode enabled, parses the response into a Go struct, and prints the result.
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
type Message struct {
Role string `json:"role"`
Content string `json:"content"`
}
type SentimentResult struct {
Sentiment string `json:"sentiment"`
Confidence float64 `json:"confidence"`
}
func analyze(system []Message, input string) SentimentResult {
msgs := append(system, Message{Role: "user", Content: input})
body, _ := json.Marshal(map[string]any{
"model": "llama3.2",
"messages": msgs,
"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 SentimentResult{}
}
defer resp.Body.Close()
data, _ := io.ReadAll(resp.Body)
var apiResp struct {
Message struct {
Content string `json:"content"`
} `json:"message"`
}
json.Unmarshal(data, &apiResp)
var result SentimentResult
json.Unmarshal([]byte(apiResp.Message.Content), &result)
return result
}
func main() {
messages := []Message{
{Role: "system", Content: `Analyze the sentiment of the user's message.
Return JSON: {"sentiment": "positive|negative|neutral", "confidence": 0.0-1.0}
Return only the JSON. No explanation.`},
}
inputs := []string{
"I love this product, it works perfectly!",
"The delivery was late and the box was damaged.",
"I ordered a blue shirt in size medium.",
}
for _, input := range inputs {
result := analyze(messages, input)
fmt.Printf("%-50s → %s (%.0f%%)\n", input, result.Sentiment, result.Confidence*100)
}
// I love this product, it works perfectly! → positive (92%)
// The delivery was late and the box was damaged. → negative (88%)
// I ordered a blue shirt in size medium. → neutral (95%)
}