当我试图用go lang调用该值时出错

问题描述 投票:0回答:1

我刚刚开始学习这个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": "[email protected]",
      "publishdate": "26.04.2017",
      "image": "http://dummyimage.com/188x199.png/cc0000/ffffff"
    },
    {
      "title": "mus vivamus vestibulum sagittis",
      "author": "Analise",
      "content": "[email protected]",
      "publishdate": "13.03.2017",
      "image": "http://dummyimage.com/182x113.bmp/ff4444/ffffff"
    }
  ]
}

This is the directory

json go
1个回答
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": "[email protected]",
      "publishdate": "26.04.2017",
      "image": "http://dummyimage.com/188x199.png/cc0000/ffffff"
    },
    {
      "title": "mus vivamus vestibulum sagittis",
      "author": "Analise",
      "content": "[email protected]",
      "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)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.