Skip to content

Instantly share code, notes, and snippets.

@ogryzek
Last active May 17, 2016 06:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ogryzek/89f1b5623701b0fdeddbcf14f4798d29 to your computer and use it in GitHub Desktop.
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.
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))
}
@ogryzek
Copy link
Author

ogryzek commented May 16, 2016

example request

curl -d '{"data": [{"to":"drew","from":"jo","greeting":"Hey"},{"to":"lori", "from":"yuri","greeting":"what up?"}]}' http://localhost:3000

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment