package main
import (
"encoding/json"
"net/http"
"strconv"
"log"
)
func GetJSONPosts (w http.ResponseWriter, r *http.Request) {
somePosts := CreateSamplePosts
enc := json.NewEncoder(w)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
err := enc.Encode(somePosts)
if err != nil {
log.Println(err)
}
/* for _, somePost := range somePosts() {
err := enc.Encode(somePost)
if err != nil {
log.Println(err)
}
}*/
}
func CreateSamplePosts () JSONPosts {
posts := JSONPosts{}
for i := 0; i < 5; i++ {
title := "Post " + strconv.Itoa(i+1)
content := "This is content for post " + strconv.Itoa(i+1)
post := JSONPost{Title: title, Content: content}
posts = append(posts, post)
}
return posts
}
package main
import (
"html/template"
)
type Page struct {
Title string //`json:"title"`
Content template.HTML //`json:"content"`
PagePosts []Post
}
type Pages []Page
type Post struct {
Title string //`json:"title"`
Content template.HTML //`json:"content"`
}
type Posts []Post
type JSONPost struct {
Title string `json:"Title"`
Content string `json:"Content"`
}
type JSONPosts []JSONPost
When I run this in the browser nothing shows. The error printed at the console is:
2015/08/12 21:46:06 json: unsupported type: func() main.JSONPosts
Now note in the first section of code the commented part works. Well sort of. No errors and something is output but since it is doing each struct item piecemeal the json is missing the commas between items. Been googling around and not been able to figure out what I am doing wrong.
Obviously there is more to this code in other pieces but the rest of it is more the routes and main program/server.
Ken