This is a creation in Article, where the information may have evolved or changed.
Golang's introduction to Web Programming sample, chat a few lines, simple understanding.
Package Mainimport ("FMT" "Html/template" "Log" "Net/http" "strings") Func Sayhelloname (w http. Responsewriter, R *http. Request) {R.parseform ()//resolves the parameters passed by the URL, the body of the response package for post (request body)//NOTE: If the Parseform method is not called, the data fmt for the form cannot be obtained below. PRINTLN (R.form)//This information is output to the server-side printing information \fmt. PRINTLN ("Path", R.url. Path) fmt. PRINTLN ("scheme", R.url. Scheme) fmt. Println (r.form["Url_long"]) for k, V: = Range R.form {fmt. Println ("Key:", K) fmt. Println ("Val:", Strings. Join (V, ""))}fmt. fprintf (W, "Hello wow!")//This write to W is the output to the client's}func login (w http. Responsewriter, R *http. Request) {fmt. Println ("Method:", R.method)//Gets the method of the request if R.method = = "Get" {T, _: = template. Parsefiles ("login.html") T.execute (W, Nil)} else {r.parseform ()//parse URL passed parameters, for post the body of the parsing response package (request body)//Requested login data , then execute the login logic to judge the FMT. Println ("Username:", r.form["username"]) fmt. Println ("Password:", r.form["password"]) fmt. fprintf (W, "Hello%s!", r.form["username"])//This write to W is the output to the client's}}func main () {var err errorhttp. Handlefunc ("/", Sayhelloname)//set access to the routed HTTP. Handlefunc ("/login", login)//set access to the route err = http. Listenandserve (": 9090", nil)//Set the listening port if err! = Nil {log. Fatal ("Listenandserve:", Err)}}
Go Programming Router functions:
Package Mainimport ("FMT" "net/http") type Mymux struct {}//set router func (P *mymux) servehttp (w http. Responsewriter, R *http. Request) {if r.url. Path = = "/" {Sayhelloname (W, R) return}http. NotFound (W, R) Return}func Sayhelloname (w http. Responsewriter, R *http. Request) {fmt. fprintf (W, "Hello Gerryyang, Version 2!\n")}func Main () {mux: = &mymux{}http. Listenandserve (": 9090", MUX)}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.