Skip to content

Instantly share code, notes, and snippets.

@ogryzek
Last active July 12, 2016 22:17
Show Gist options
  • Save ogryzek/6303d4a7a22136beb0659f70a3cc3fcb to your computer and use it in GitHub Desktop.
Save ogryzek/6303d4a7a22136beb0659f70a3cc3fcb to your computer and use it in GitHub Desktop.
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
var ThirdPartyApi = "http://www.coolsongssite.api"
type IncomingRequest struct {
username string `json:"username"`
password string `json:"password"`
songs []IncomingSong `json:"songs"`
}
type OutgoingRequest struct {
username string `json:"username"`
password string `json:"password"`
songs []OutgoingSong `json:"songs"`
}
type IncomingSong struct {
artist string `json:"artist"`
album string `json:"album"`
title string `json:"title"`
}
type OutgoingSong struct {
musician string `json:"musician"`
record string `json:"record"`
name string `json:"name"`
}
func main() {
http.HandleFunc("/songs/create", createSong)
http.ListenAndServe(":8080", nil)
}
func createSong(rw http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(req.Body)
var incomingRequest IncomingRequest
decoder.Decode(&incomingRequest)
outgoingRequest := incomingRequestToOutgoingRequest(incomingRequest)
r, _ := json.Marshal(outgoingRequest)
request, _ := http.NewRequest("POST", ThirdPartyApi, bytes.NewBuffer(r))
request.Header.Set("Content-Type", "application/json")
client := http.Client{}
response, _ := client.Do(request)
fmt.Fprintln(rw, response)
}
func incomingRequestToOutgoingRequest(inc IncomingRequest) OutgoingRequest {
outgoingRequest := OutgoingRequest{
username: inc.username,
password: inc.password,
}
for _, s := range inc.songs {
outgoingRequest.songs = append(
outgoingRequest.songs, OutgoingSong{
musician: s.artist,
record: s.album,
name: s.title,
},
)
}
return outgoingRequest
}
package main
import (
"testing"
)
func TestincomingRequestToOutgoingRequest(t *testing.T) {
incomingRequest := IncomingRequest{
username: "myuser",
password: "mypassword",
}
var songs []IncomingSong
songs = append(
songs, IncomingSong{
artist: "White Rabbits",
album: "Milk Famous",
title: "I'm Not Me",
},
)
outgoingRequest := incomingRequestToOutgoingRequest(incomingRequest)
if outgoingRequest.songs[0].musician != "White Rabbits" {
t.Error("Expected musican name to be 'White Rabbits'. Got: ", outgoingRequest.songs[0].musician)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment