The program reads the file, but then substitutes something else in for data. Just put the data in the value marshaled to the output.
type Event struct {
Specversion string `json:"specversion"`
ID uuid.UUID `json:"id"` /// uuid
Source string `json:"source"`
Type string `json:"type"`
Time time.Time `json:"time"`
Data string `json:"data"` /* <= change to string */
}
func main() {
if len(os.Args) < 1 { //checking for provided argument if the first arg satisfy then use read file
fmt.Println("Usage : " + os.Args[0] + " file name")
help()
os.Exit(1)
}
Data, err := ioutil.ReadFile(os.Args[1])
if err != nil {
fmt.Println("Cannot read the file or file does not exists")
os.Exit(1)
}
e := Event{
Specversion: "1.0",
ID: uuid.New(),
Source: "CSS",
Type: "", // user input -p or -u,
Time: time.Now(),
Data: string(Data), /* <= stuff data into output value */
}
out, _ := json.MarshalIndent(e, "", " ")
fmt.Println(string(out))
}
Run it on the playground to get results as requested in the question.
Perhaps the \r\n in the output are the problem. Remove carriage return and line feed from the JSON before encoding the result:
replacer := strings.NewReplacer("\r", "", "\n", "")
Data = []byte(replacer.Replace(string(Data)))
Run it on the playground.
If you intent is to include the JSON as JSON instead of quoting the JSON as string, then use json.RawMessage:
type Event struct {
Specversion string `json:"specversion"`
ID uuid.UUID `json:"id"` /// uuid
Source string `json:"source"`
Type string `json:"type"`
Time time.Time `json:"time"`
Data json.RawMessage `json:"data"` /* <= change to json.RawMessage */
}
func main() {
if len(os.Args) < 1 { //checking for provided argument if the first arg satisfy then use read file
fmt.Println("Usage : " + os.Args[0] + " file name")
help()
os.Exit(1)
}
Data, err := ioutil.ReadFile(os.Args[1])
if err != nil {
fmt.Println("Cannot read the file or file does not exists")
os.Exit(1)
}
e := Event{
Specversion: "1.0",
ID: uuid.New(),
Source: "CSS",
Type: "", // user input -p or -u,
Time: time.Now(),
Data: Data, /* <== use data as is */
}
out, _ := json.MarshalIndent(e, "", " ")
fmt.Println(string(out))
}
Run it on the playground to view nested json. You show a quoted string in the question, but perhaps this output is what you really want.