我刚刚开始学习这个Go Lang编程,现在我仍然坚持使用[]的东西,我尝试使用Go Lang创建一个博客,并且我使用模板,那里'没有问题的模板,只是我想附加一个我从json文件中获取的数据。
如果我只是获取数据并通过文件发送它已经完成,但问题是当我试图将slug附加到数据时(因为json文件我没有获取slug url)。
这就是为什么我想获得帖子的标题然后用它制作一个slug,然后
package main
import (
"encoding/json"
"fmt"
"github.com/gosimple/slug"
"html/template"
"io/ioutil"
"net/http"
"os"
)
type Blog struct {
Title string
Author string
Header string
}
type Posts struct {
Posts []Post `json:"posts"`
}
type Post struct {
Title string `json:"title"`
Author string `json:"author"`
Content string `json:"content"`
PublishDate string `json:"publishdate"`
Image string `json:"image"`
}
type BlogViewModel struct {
Blog Blog
Posts []Post
}
func loadFile(fileName string) (string, error) {
bytes, err := ioutil.ReadFile(fileName)
if err != nil {
return "", err
}
return string(bytes), nil
}
func loadPosts() []Post {
jsonFile, err := os.Open("source/posts.json")
if err != nil {
fmt.Println(err)
}
fmt.Println("Successfully open the json file")
defer jsonFile.Close()
bytes, _ := ioutil.ReadAll(jsonFile)
var post []Post
json.Unmarshal(bytes, &post)
return post
}
func handler(w http.ResponseWriter, r *http.Request) {
blog := Blog{Title: "asd", Author: "qwe", Header: "zxc"}
posts := loadPosts()
viewModel := BlogViewModel{Blog: blog, Posts: posts}
t, _ := template.ParseFiles("template/blog.html")
t.Execute(w, viewModel)
}
错误显示在主要功能
中func main() {
posts := loadPosts()
for i := 0; i < len(posts.Post); i++ { // it gives me this error posts.Post undefined (type []Post has no field or method Post)
fmt.Println("Title: " + posts.Post[i].Title)
}
// http.HandleFunc("/", handler)
// fs := http.FileServer(http.Dir("template"))
// http.Handle("/assets/css/", fs)
// http.Handle("/assets/js/", fs)
// http.Handle("/assets/fonts/", fs)
// http.Handle("/assets/images/", fs)
// http.Handle("/assets/media/", fs)
// fmt.Println(http.ListenAndServe(":9000", nil))
}
我已经尝试解决了几个小时但是我碰到了墙,我认为这是可能的,但我只是找不到路,我不知道什么是好的用于解决问题的关键字。 如果我已经解释得好或不好,我也不会这样做。请帮帮我,谢谢
这是JSON文件格式
{
"posts": [
{
"title": "sapien ut nunc",
"author": "Jeni",
"content": "jgwilt0@mapquest.com",
"publishdate": "26.04.2017",
"image": "http://dummyimage.com/188x199.png/cc0000/ffffff"
},
{
"title": "mus vivamus vestibulum sagittis",
"author": "Analise",
"content": "adonnellan1@biblegateway.com",
"publishdate": "13.03.2017",
"image": "http://dummyimage.com/182x113.bmp/ff4444/ffffff"
}
]
}
答案 0 :(得分:3)
你的loadPost方法返回[]Post
。您对Post
的定义不包含attribute Post
。你的Posts
结构确实如此。
这是一个经过修改的工作示例。为简洁起见,我没有定义你的其他结构。
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
)
var rawJson = `{
"posts": [
{
"title": "sapien ut nunc",
"author": "Jeni",
"content": "jgwilt0@mapquest.com",
"publishdate": "26.04.2017",
"image": "http://dummyimage.com/188x199.png/cc0000/ffffff"
},
{
"title": "mus vivamus vestibulum sagittis",
"author": "Analise",
"content": "adonnellan1@biblegateway.com",
"publishdate": "13.03.2017",
"image": "http://dummyimage.com/182x113.bmp/ff4444/ffffff"
}
]
}`
type Data struct {
Posts []struct {
Title string `json:"title"`
Author string `json:"author"`
Content string `json:"content"`
Publishdate string `json:"publishdate"`
Image string `json:"image"`
} `json:"posts"`
}
func loadFile(fileName string) (string, error) {
bytes, err := ioutil.ReadFile(fileName)
if err != nil {
return "", err
}
return string(bytes), nil
}
func loadData() (Data, error) {
var d Data
// this is commented out so that i can load raw bytes as an example
/*
f, err := os.Open("source/posts.json")
if err != nil {
return d, err
}
defer f.Close()
bytes, _ := ioutil.ReadAll(f)
*/
// replace rawJson with bytes in prod
json.Unmarshal([]byte(rawJson), &d)
return d, nil
}
func main() {
data, err := loadData()
if err != nil {
log.Fatal(err)
}
for i := 0; i < len(data.Posts); i++ {
fmt.Println("Title: " + data.Posts[i].Title)
}
/*
// you can also range over the data.Posts if you are not modifying the data then using the index is not necessary.
for _, post := range data.Posts {
fmt.Println("Title: " + post.Title)
}
*/
}
仅为文件修改
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
)
type Data struct {
Posts []struct {
Title string `json:"title"`
Author string `json:"author"`
Content string `json:"content"`
Publishdate string `json:"publishdate"`
Image string `json:"image"`
} `json:"posts"`
}
func loadData() (Data, error) {
var d Data
b, err := ioutil.ReadFile("source/posts.json")
if err != nil {
return d, err
}
err = json.Unmarshal(b, &d)
if err != nil {
return d, err
}
return d, nil
}
func main() {
data, err := loadData()
if err != nil {
log.Fatal(err)
}
for _, post := range data.Posts {
fmt.Println("Title: " + post.Title)
}
}