package main
import (
"encoding/json"
"fmt"
"errors"
)
type Post struct {
Title string
Text string
}
func NewPostFromIncomingPost(incomingPost map[string]string) (*Post, error) {
post := &Post{}
if title, exists := incomingPost[`name`]; exists {
post.Title = title
} else if title, exists := incomingPost[`title`]; exists {
post.Title = title
} else {
return nil, errors.New(`title not found`)
}
if text, exists := incomingPost[`text`]; exists {
post.Text = text
} else if text, exists := incomingPost[`description`]; exists {
post.Text = text
} else {
return nil, errors.New(`text not found`)
}
return post, nil
}
func main() {
jsonSource1 := []byte(`{"title": "Title", "text": "Text"}`)
jsonSource2 := []byte(`{"name": "Title", "description": "Text"}`)
var incomingPost1 map[string]string
if err := json.Unmarshal(jsonSource1, &incomingPost1); err != nil {
panic(err)
}
post1, err := NewPostFromIncomingPost(incomingPost1)
fmt.Printf("post1: %+v\nerr: %+v\n\n", post1, err)
var incomingPost2 map[string]string
if err := json.Unmarshal(jsonSource2, &incomingPost2); err != nil {
panic(err)
}
post2, err := NewPostFromIncomingPost(incomingPost2)
fmt.Printf("post2: %+v\nerr: %+v\n\n", post2, err)
}