Beispiel #1
0
func main() {

	rest.AddRoute("/test", "GET", RouteTest)
	rest.AddRoute("/test/:str", "PUT", RouteTestWithStr)
	rest.AddRoute("/test/:id", "DELETE", RouteTestWithInt)
	rest.AddRoute("/test", "POST", RouteTestWithJson)
	rest.AddRoute("/test2", "POST", RouteTestWithJson2)
	rest.AddRoute("/test/:str/static/:id/last", "PUT", RouteTestWithStrInt)

	fmt.Println("listening")
	rest.ListenAndServe("0.0.0.0:9081", nil)

}
Beispiel #2
0
func ExamplePing() {

	// Add our service that implements the rest.Routable interface to our
	// endpoint. We can also add simple lambda functions to our endpoint.
	rest.AddService(new(PingService))
	rest.AddRoute("/simple", "POST", func(tick int) int { return tick })

	// The endpoint is started like any other http.Server.
	go rest.ListenAndServe(":11263", nil)

	time.Sleep(30 * time.Millisecond)

	// The rest package also provides a way to query a REST endpoint by
	// incrementally building a REST request. The body of the query can be set
	// via the SetBody() function which will serialize the object to JSON using
	// the encoding.json package.
	simpleResp := rest.NewRequest("http://localhost:11263", "POST").
		SetPath("/simple").
		SetBody(123).
		Send()

	// The rest.Response object contains the result of the REST request and can
	// be used to deserialize the JSON body into the provided object using the
	// encoding.json package.
	var tick int
	if err := simpleResp.GetBody(&tick); err != nil {
		panic("Whoops! " + fmt.Sprint(err))
	}
	fmt.Println("ping-simple:", tick)

	// The REST client can also be customized by manually creating a rest.Client
	// which can then be used to create REST requests. rest.Client embdeds an
	// http.Client struct which can be used to customize the HTTP requests.
	client := &rest.Client{Host: "http://localhost:11263", Root: "/ping"}
	clientResp := client.NewRequest("PUT").
		SetPath("%d", 321).
		AddParam("test", "321").
		AddParam("test2", "3212").
		Send()

	if err := clientResp.GetBody(&tick); err != nil {
		panic("Whoops!")
	}
	fmt.Println("ping-client:", tick)

	// The REST client can check if a response timed out.
	dialer := net.Dialer{Timeout: 500 * time.Millisecond}
	clientTime := &rest.Client{
		Host: "http://localhost:11263",
		Root: "/ping",
		Client: &http.Client{
			Transport: &http.Transport{Dial: dialer.Dial},
			Timeout:   500 * time.Millisecond,
		},
	}
	timeoutResp := clientTime.NewRequest("GET").
		SetPath("delay").
		Send()

	if err := timeoutResp.GetBody(&tick); err == nil {
		panic("Whoops! Should time out" + fmt.Sprint(tick))
	}

	// Output:
	// ping-simple: 123
	// ping-client: 321
}