2017-11-01 10 views
-1

나는 json이 구조체를 인코딩하는 내 서버에서 매우 간단한 http 공감을 가지고 있습니다. 하지만 그것의 공백을 보내 그냥 {}JSON 인코딩 빈 반환 골란

나는 그것을 잘못하고 있지만 나는 아무런 오류가 있는지 모르겠다. 이건 내 JSON 인코딩입니다 : 데이터를 종료하려면 잡에

// Set uuid as string to user struct 
    user := User{uuid: uuid.String()} 
    fmt.Println(user) // check it has the uuid 

    responseWriter.Header().Set("Content-Type", "application/json") 
    responseWriter.WriteHeader(http.StatusCreated) 

    json.NewEncoder(responseWriter).Encode(user) 

있습니다

Content-Type application/json 
Content-Length 3 
STATUS HTTP/1.1 201 Created 
{} 

이 왜 나에게 UUID 데이터를 제공하지 않는 이유는 무엇입니까? 내 인코딩에 문제가 있습니까?

+6

수출 필드 이름을. 가능한 중복 https://stackoverflow.com/questions/26327391/go-json-marshalstruct-returns를 참조하십시오. –

+0

아프면 작동하는지 확인해보십시오. – Sir

+3

[json.Marshal (struct)의 가능한 복제본은 "{}"(https://stackoverflow.com/questions/26327391/go-json-marshalstruct-returns) – tgogos

답변

2

the first character of the identifier's name a Unicode upper case letter (Unicode class "Lu")으로 필드 이름을 내 보냅니다.

이 시도 :

package main 

import (
    "encoding/json" 
    "fmt" 
    "log" 
    "net/http" 
) 

type User struct { 
    Uuid string 
} 

func handler(responseWriter http.ResponseWriter, r *http.Request) { 
    user := User{Uuid: "id1234657..."} // Set uuid as string to user struct 
    fmt.Println(user)     // check it has the uuid 
    responseWriter.Header().Set("Content-Type", "application/json") 
    responseWriter.WriteHeader(http.StatusCreated) 
    json.NewEncoder(responseWriter).Encode(user) 
} 

func main() { 
    http.HandleFunc("/", handler)   // set router 
    err := http.ListenAndServe(":9090", nil) // set listen port 
    if err != nil { 
     log.Fatal("ListenAndServe: ", err) 
    } 
} 

출력 (http://localhost:9090/) :

{"Uuid":"id1234657..."} 
+0

아 간단한 해결책! 대문자로 해결 :) 감사합니다 – Sir

+0

당신을 환영합니다. –