REST API client and Server - hqzhang/cloudtestbed GitHub Wiki

  1. Golang Rest Server
package main

import (
    "encoding/json"
    "log"
    "net/http"
    "io/ioutil"
    "fmt"
)
type Message struct {
    Name string
    Body string
    Time int64
}

func test(rw http.ResponseWriter, req *http.Request) {
    log.Println("enter handle()....")
    body, err := ioutil.ReadAll(req.Body)
    if err != nil {
        panic(err)
    }
    log.Println("body:"+string(body))
    var msg Message
    err = json.Unmarshal(body, &msg)
    if err != nil {
         panic(err)
    }
    log.Println("I am "+msg.Name)
    //send back
    fmt.Fprintf(rw, "I received your message...",msg )
}

func main() {
    http.HandleFunc("/test", test)
    log.Fatal(http.ListenAndServe(":8090",nil))
}

  1. Golang REST client
package main
import (
    "fmt"
    "net/http"
    "io/ioutil"
    "bytes"
    "encoding/json"
    )
type Message struct {
    Name string
    Body string
    Time int64
}

func main() {
    url := "http://localhost:8090/test"
    fmt.Println("URL:>", url)
    m := Message{"Alice", "Hello", 1294706395881547000}
    jsonb, err := json.Marshal(m)
    fmt.Println(string(jsonb) )

    req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonb))
    req.Header.Set("X-Custom-Header", "myvalue")
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    fmt.Println("send mesage:"+string(jsonStr) )
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    fmt.Println("response Status:", resp.Status)
    fmt.Println("response Headers:", resp.Header)
    body, _ := ioutil.ReadAll(resp.Body)
    fmt.Println("response Body:", string(body))
}