Go language Introduction First Go language Web program-Simple Web server

Source: Internet
Author: User


Overview


in the previous article, "Go Language Primer" The first Go Language program--helloworld, next talk about Go language Web Development Prerequisites : The first Go language Web program-a simple Web server.



Unlike other web back-end languages, the go language needs to write its own web server .





For local environment construction and basic learning, please refer to:



How to get started in the Go language install the Go Language programming environment under Windows



Go language web App: IBM's Cloud Platform Bluemix experience-Create a Go language Web application, add and use language translation services


Web server Code





Google provides a service on http://chart.apis.google.com that automatically transforms form data into charts. However, the service is difficult to interact with because you need to put the data in the URL as a query. This program provides a better interface for a data format: given a small piece of text, it will call the chart server to generate a QR code (code), which is a dot matrix of encoded text. The image can be captured by your phone camera and interpreted as a string, such as a URL, which eliminates the hassle of typing a URL on a small phone keypad.



The following is a complete procedure, followed by an explanation.


package main

import (
    "flag"
    "html / template"
    "log"
    "net / http"
)

var addr = flag.String ("addr", ": 1718", "http service address") // Q = 17, R = 18

var templ = template.Must (template.New ("qr"). Parse (templateStr))

func main () {
    flag.Parse ()
    http.Handle ("/", http.HandlerFunc (QR))
    err: = http.ListenAndServe (* addr, nil)
    if err! = nil {
        log.Fatal ("ListenAndServe:", err)
    }
}

func QR (w http.ResponseWriter, req * http.Request) {
    templ.Execute (w, req.FormValue ("s"))
}

const templateStr = `
<html>
<head>
<title> QR Link Generator </ title>
</ head>
<body>
{{if.}}
<img src = "http://chart.apis.google.com/chart?chs=300x300&cht=qr&choe=UTF-8&chl= {{.}}" />
<br>
{{.}}
<br>
<br>
{{end}}
<form action = "/" name = f method = "GET"> <input maxLength = 1024 size = 70
name = s value = "" title = "Text to QR Encode"> <input type = submit
value = "Show QR" name = qr>
</ form>
</ body>
</ html>
`

The code before main should be easier to understand. We set a default port for the server with a flag. The template variable templ is officially interesting. The HTML template it builds will be executed by the server and displayed on the page. We will discuss this in detail later.

The main function parses the parameter flags and uses the mechanism we discussed to bind the QR function to the root path of the server. Then call http.ListenAndServe to start the server; it will be blocked while the server is running.

QR only accepts requests containing form data and executes templates for the data in form value s.

The template package html / template is very powerful; the program is just a taste. Essentially, it rewrites the HTML text by passing the extracted elements (in this case form values) from the data item to templ.Execute at runtime. In the template text (templateStr), the text enclosed by the double braces indicates the action of the template. The snippet from {{if.}} To {{end}} will only be executed if the value of the current data item (here a dot.) Is not empty. That is, when the string is empty, this part of the template segment is ignored.

Two of the paragraphs {{.}} Indicate that the data is to be displayed in a template (ie the query string is displayed on a web page). The HTML template package will automatically escape the text, so the display of the text is safe.

The remaining template strings are just the HTML that will be displayed when the page loads. If you can't understand this explanation, please refer to the documentation for more explanation of the template package.

You finally got your wish: a web server implemented in a few lines of code, containing some data-driven HTML text. Go is powerful enough to solve many things in a short and clever way.

Compile and run access
Create a directory in the Src directory under the Go installation directory. My Go is installed on the D drive.

So I created a "web1" folder in the D: \ Go \ src \ directory and created a new "web1.go" file. Copy and paste the above code into the file and save it.

Compile
You can execute the command in the command line window: go install web1

To complete the compilation, the web1 exe will be generated in the D: \ Go \ bin directory after the compilation is completed.



carried out
After compiling by the above method, double-click to run.

You can also switch to the directory where the file is located at the command line, for example: D: \ Go \ src \ web1

Then execute: go run web1.go

The result is:



Click Allow access.

access
Visit in the browser, view the effect, open the browser, enter: http: // localhost: 1718 /, the results are as follows:



Enter a URL in the text box, such as (http://blog.csdn.net/testcs_dn), click Show QR, a QR code image will be generated



Scan this QR code and see





summary
Unlike other web backend languages, Go requires writing its own web server.

Here is just a simple example of compiling and running to see the effect and find the feeling.













"Getting Started With Go" First Go Web Program-Simple Web Server

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.