Last active
May 17, 2016 06:00
-
-
Save ogryzek/89f1b5623701b0fdeddbcf14f4798d29 to your computer and use it in GitHub Desktop.
Take a json request and output json with the same data but different keys.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"net/http" | |
) | |
type Greetings struct { | |
Greetings []Greeting `json:"data"` | |
} | |
type Greeting struct { | |
From string `json:"from"` | |
To string `json:"to"` | |
Greeting string `json:"greeting"` | |
} | |
type RelationShip struct { | |
Messages []Message `json:"data"` | |
} | |
type Message struct { | |
From string `json:"from"` | |
To string `json:"to"` | |
Message string `json:"message"` | |
} | |
func main() { | |
http.HandleFunc("/", Greet) | |
http.ListenAndServe(":3000", nil) | |
} | |
func Greet(rw http.ResponseWriter, request *http.Request) { | |
decoder := json.NewDecoder(request.Body) | |
var greetings Greetings | |
err := decoder.Decode(&greetings) | |
if err != nil { | |
panic(err) | |
} | |
for _, g := range greetings.Greetings { | |
fmt.Printf("%s, to %s from %s.\n", g.Greeting, g.To, g.From) | |
} | |
var relationShip RelationShip | |
for _, g := range greetings.Greetings { | |
relationShip.Messages = append( | |
relationShip.Messages, Message{ | |
To: g.To, From: g.From, Message: g.Greeting, | |
}, | |
) | |
} | |
r, err := json.Marshal(&relationShip) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Fprintln(rw, string(r)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
example request