当我尝试使用go lang调用值时遇到错误

用户7857373:

我刚刚开始学习Go语言编程,现在我陷入[]的问题,我尝试使用Go语言创建博客,并且我使用的是模板,模板没有问题,只是我想要的附加我从json文件获得的数据。

如果我只是获取数据并通过文件发送它,那么它已经完成了,但是问题是当我尝试将数据块附加到数据上时(因为json文件中没有数据块url。

这就是为什么我要获取帖子标题,然后对其进行编辑,然后

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"
    }
  ]
}

这是目录

reticentroot:

您是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)
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

当我尝试使用锚标记从我的jsp页面调用servlet页面时,显示错误

当我尝试使用指针的别名时,g ++返回错误

当我尝试在Eclipse中使用Proguard时会返回错误

当我尝试使用自身更新属性时,JSLint抱怨

当我尝试插入新记录时,Hibernate 使用更新

当我尝试使用按钮添加QTabWidget时崩溃

当我尝试使用BeautifulSoup从网站抓取时缺少文本

当我尝试在导航中使用道具时出错

当我尝试使用 .txt 文件时,.exe 程序崩溃

当我尝试使用方法时,它会出错

当我尝试使用npm我安装我的项目包时出现错误

当我尝试使用BufferedReader将整数输入存储到数组时遇到数字格式异常

尝试同时使用GO解析网站时遇到多个错误

当我尝试使用 Axios 调用 Instagram API 时,我被“CORS 政策阻止”

TypeError:“ NoneType”对象不可调用:当我尝试使用openpyxl在Python中使用Excel文件时显示此错误

当我尝试在React Native中使用AsyncStorage保存值时,但是当我尝试检索值时,我有{“ _U”:0,“ _V”:0,“ _W”:null,“ _X”:null}

当我尝试使用 useState 查看我的文本时,为什么会出现错误?

当我尝试使用 JavaScript 数组方法时,我不断收到错误消息

当我尝试使用 Spring 和 file.properties 时,我看到错误

每当我尝试使用函数时,我总是收到编译器错误

当我尝试在我的 flutter 应用程序中使用 firebase 时,它会产生错误

我是使用mysql的新手-当我尝试创建表时,出现以下错误

当我尝试迁移配置文件表时,出现错误。我正在使用laravel 5.1

我正在使用elasticserach-1.4.1,当我尝试创建索引时,出现以下错误

当我尝试使用我的 API 插入注册时,错误 #1064 MySQL

当我尝试使用 ssh 推送时,Git 尝试使用全局用户

当我尝试在ubuntu中运行Eclipse时遇到此错误,请帮助

当我尝试在React.JS中导入常量时遇到错误

当我尝试在Bootstrap3上传递网站时遇到javascript错误