2017-12-30 2 views
0

방금 ​​Go Lang 프로그래밍을 배우기 시작했는데 이제는 [] 가지로 붙어 있습니다. Go Lang을 사용하여 블로그를 만들려고했습니다. 템플릿을 사용하는 m, 템플릿에 아무런 문제가 없습니다, 그냥 json 파일에서 가져온 데이터를 추가하고 싶습니다.은 go lang으로 값을 호출하려고 시도했을 때 오류가 발생했습니다

내가 (데이터에 슬러그를 추가하려고 할 때 난 그냥 데이터를 가지고 이미 끝났다 파일을 보내,하지만 문제는 경우 때문에 그것에서 더 슬러그 URL을 얻지 JSON 파일.

나는 다음과 슬러그을 게시물의 제목을 얻을하려는 이유

그 다음, 오류가

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)) 

} 

나는 이미 그것을 해결 교류하려고 메인 함수에서 쇼

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

입니다 시간이 많지만 벽에 부딪쳤다. 가능한 일이라고 생각하지만 나는 그 길을 찾지 못했다. 문제를 해결하기위한 좋은 키워드가 무엇인지 모르겠다. 그리고 이미 충분히 설명이 잘되어 있지 않습니까? 제발 도와주세요, 당신

감사 이는 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

답변

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) 
    } 
} 
+0

안녕, 답변 주셔서 감사합니다. 나는 그것을 시도하고 그것을 작동하지만, 내가 json 파일을 얻으려고했을 때 len 함수가 그것을 0으로 표시하는 이유는 무엇입니까? [func loadData] (https://i.imgur.com/zCK4RHi.png) 이미 당신의 [func main] (https://i.imgur.com/Rg3USd1.png)과 동일하지만 결과는 다음과 같습니다. [출력] (https://i.imgur.com/0YkayTA.png) –

+0

위 주석 처리 된 코드의 주석 처리를 제거 했습니까? 나는 그것을 파일로 편집 할 것이다. – reticentroot

+0

예 파일의 데이터를 가져와야하기 때문에 코드의 주석 처리를 제거하십시오. 그러나 그것은 같은 것이 아닙니까? 파일 안쪽에있는 rawJson과 똑같은 것이 있기 때문에? –

관련 문제