This is a creation in Article, where the information may have evolved or changed.
The go language makes Web server implementations and deployments extremely concise. Finally, you can get rid of the messy project structure and the huge size of the IDE, a glimpse of its rationale.
The first is a simple server implementation code, if it is a GET request, then loopback an this is a GET requests message, if it is a POST request, the POST request to resolve the Info field, the content is echoed back. The program can be run directly from the command line with Go Server.go BOOT.
Server. GoPackage Mainimport ("FMT" "Net/http") Func Login (w http. Responsewriter, R *http. Request) {R. Parseform() FMT. Println(r. Method) If R. Method=="GET"{FMT. fprintf(W,"This is a GET request")}else{W. Header(). Set("Access-control-allow-origin","*") FMT. Println("recived info:"R. Form) FMT. fprintf(W,r. Form. Get("Info"))}}func Main () {HTTP. Handlefunc("/login", login) If err:=http. Listenandserve(": 9000", nil); err!=nil{Fmt. Println("Listenandserve Err", err)}}
Then the browser-side page:
<! DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Go Server test</title> <script type="text/javascript" src="http// Code.jquery.com/jquery-1.4.1.js "></script><script type="Text/javascript"> function upload(){ varURL ="Http://localhost:9000/login";varSRC ={}; src["Info"]=$("Input"). Val (); $.ajax ({url:url, type:' Post ', DATA:SRC, Datatypt:' JSON ', Success: function(data){$("a"). text (data); }, Error: function(XHR, msg){Alert (msg); } }); }</script></head><body>Input content:<input name="Info"></input> <inputtype="Submit"value="Commit" onclick="Upload" ( ) "> <div>Echo Content:<a></a></div></body></html>
Also quite simple, open directly in the browser, and then enter a string in the input box, click Submit to send a POST request to the server. The server returns the string back:
If Http://localhost:9000/login is accessed directly in the browser, it is equivalent to sending a GET request, and the browser receives a message:
Both the client and server-side code structure is very concise, nothing more than a server-side registration route and corresponding processing functions, and then write the resulting message to responsewriter; The client chooses the server-side route and sends its own data over Ajax. The callback handler function succeeds. Of course, a good server design needs to consider security, performance and many other factors, here is not detailed.