Skip to content

Latest commit

 

History

History
111 lines (75 loc) · 6.91 KB

File metadata and controls

111 lines (75 loc) · 6.91 KB

#8.3 REST RESTful is the most popular software architecture on the internet today, due to its clear, strict standard, easy to understand and expand, more and more websites are based on it. In this section, we are going to know what it really is and how to use this architecture in Go.

##What is REST? The first declaration of the concept of REST(REpresentational State Transfer) was in 2000 in Roy Thomas Fielding's doctoral dissertation, who is the co-founder of HTTP. It's a architecture constraints and principles, anything implemented this architecture we call them RESTful.

Before we understand what is REST, we need to cover following concepts:

  • Resources

    REST is the Presentation Layer State Transfer, where presentation layer is actually resource presentation layer.

    So what are resources? A picture, a document or a video, etc. These can all be resources and located by URI.

  • Representation

    Resources are specific entity information, it can be showed with variety of ways in presentation layer. For instances, a TXT document can be represented as HTML, JSON, XML, etc; a image can be represented as jpg, png, etc.

    Use URI to identify a resource, but how to determine its specific manifestations of it? You should use Accept and Content-Type in HTTP request header, these two fields are the description of presentation layer.

  • State Transfer

    An interactive process happens between client and server when you visit a website. In this process, certain data related to the state change should be saved; however, HTTP is stateless, so we need to save these data on the server side. Therefore, if the client wants to change the data and inform the server-side state changes, it has to use some way to tell server.

    Most of time, the client informs server through HTTP. Specifically, it has four operations: GET, POST, PUT, DELETE, where GET to obtain resources, POST to create or update resources, PUT to update resources and DELETE to delete resources.

In conclusion of above explanations:

  • (1)Every URI reresented a kind of resource.
  • (2)A representation layer for transferring resources between clients and servers.
  • (3)Clients use four operation of HTTP to operation resources to implement "Presentation Layer State Transfer".

The most important principle of web applications that implement REST is that interactive between clients and servers are stateless, and every request should include all needed information. If the server restart at anytime, clients should not get notification. In addition, requests can be responded by any server of same service, which is good for cloud computing. What's more, because it's stateless, clients can cache data for performance improvement.

Another important principle of REST is system delamination, which means components have no way to have direct interaction with components in other layers. This can limit system complexity and improve the independence of the underlying.

Figure 8.5 REST architecture

When the constraint condition of REST apply to the whole application, it can be extended to have huge amounts of clients. It also reduced interactive delay between clients and servers, simplified system architecture, improved visibility of sub-systems interaction.

Figure 8.6 REST's expansibility.

##RESTful implementation Go doesn't have direct support for REST, but because RESTful is HTTP-based, so we can use package net/http to achieve them own. Of course we have to do some modification in order to implement REST. REST uses different methods to handle corresponding resources, many existed applications are claiming to be RESTful, in fact, they didn't not really realize REST. I'm going to put these applications into several levels depends on the implementation of methods.

Figure 8.7 REST's level.

Above picture shows three levels that are implemented in current REST, we may not follow all the rules of REST when we develop our applications because sometimes its rules are not fit for all possible situations. RESTful uses every single HTTP method including DELETE and PUT, but in many cases, HTTP clients can only send GET and POST requests.

  • HTML standard allows clients send GET and POST requests through links and forms, it's not possible to send PUT or DELETE requests without AJAX support.
  • Some firewalls intercept PUT and DELETE requests, clients have to use POST in order to implement them. RESTful services in charge of finding original HTTP methods and restore them.

We now can simulate PUT and DELETE by adding hidden field _method in POST requests, but you have to convert in your servers before processing them. My applications are using this way to implement REST interfaces; sure you can easily implement standard RESTful in Go as following example:

package main

import (
	"fmt"
	"github.com/drone/routes"
	"net/http"
)

func getuser(w http.ResponseWriter, r *http.Request) {
	params := r.URL.Query()
	uid := params.Get(":uid")
	fmt.Fprintf(w, "you are get user %s", uid)
}

func modifyuser(w http.ResponseWriter, r *http.Request) {
	params := r.URL.Query()
	uid := params.Get(":uid")
	fmt.Fprintf(w, "you are modify user %s", uid)
}

func deleteuser(w http.ResponseWriter, r *http.Request) {
	params := r.URL.Query()
	uid := params.Get(":uid")
	fmt.Fprintf(w, "you are delete user %s", uid)
}

func adduser(w http.ResponseWriter, r *http.Request) {
	params := r.URL.Query()
	uid := params.Get(":uid")
	fmt.Fprint(w, "you are add user %s", uid)
}

func main() {
	mux := routes.New()
	mux.Get("/user/:uid", getuser)
	mux.Post("/user/:uid", modifyuser)
	mux.Del("/user/:uid", deleteuser)
	mux.Put("/user/", adduser)
	http.Handle("/", mux)
	http.ListenAndServe(":8088", nil)
}

This sample shows you have to write a REST application. Our resources are users, and we use different functions for different methods. Here we imported a third-party package github.com/drone/routes, we talked about how to implement customized router in previous chapters; this package implemented very convenient router mapping rules, and it's good for implementing REST architecture. As you can see, REST requires you have different logic process for different methods of same resources.

##Summary REST is a kind of architecture style, it learnt successful experiences from WWW: stateless, centered on resources, fully used HTTP and URI protocols, provides unified interfaces. These superiority let REST become more popular web services standard. In a sense, by emphasizing the URI and the early Internet standards such as HTTP, REST is a large application Web-server era before the return. Currently Go For REST support is still very simple, by implementing a custom routing rules, we can think that a different method to achieve different handle, thus achieving a REST architecture.

##Links