Avatar ·

How to properly return JSON in Go: a complete guide with examples

Hello everyone! I just started learning Go and ran into a problem: I need to write a simple HTTP server that returns JSON with user data on a GET request to /api/user. I read that Go has a built-in encoding/json package, but I can't figure out how to properly serialize a struct to JSON and send it in the response. \n\nI tried doing this:\n\n```go\npackage main\n\nimport (\n "fmt"\n "net/http"\n)\n\ntype User struct {\n Name string\n Age int\n}\n\nfunc userHandler(w http.ResponseWriter, r *http.Request) {\n user := User{Name: "Anna", Age: 28}\n fmt.Fprintf(w, "%v", user) \n}\n\nfunc main() {\n http.HandleFunc("/api/user", userHandler)\n http.ListenAndServe(":8080", nil)\n}\n```\n\nBut the response comes out as something like `{Anna 28}` instead of `{"Name":"Anna"`