Go builds a web server

Time:2020-12-4

We can use HTTP packages to set up a web server

 

1 package main
 2 
 3 import (
 4     "fmt"
 5     "log"
 6     "strings"
 7     "net/http"
 8 )
 9 
10 func sayHelloName(w http.ResponseWriter,r *http.Request){
11 R. parseform() // parsing parameters
12     fmt.Println(r.Form)
13     fmt.Println("path",r.URL.Path)
14     fmt.Println("scheme",r.URL.Scheme)
15     fmt.Println(r.Form["url_long"])
16     for k,v := range r.Form{
17         fmt.Println("key",k)
18         fmt.Println("val",strings.Join(v,""))
19     }
20     fmt.Fprintf(w,"Hello astaxie!")
21 }
22 
23 func main(){
twenty-four http.HandleFunc ("/", sayhelloname) // set the access route
25     err :=  http.ListenAndServe (": 9090", Nil) // set the listening port
26     if err != nil{
27         log.Fatal("ListenAndServer Failed:",err)
28     }
29 }

 

The above code, after we build it, will execute it web.exe At this time, the HTTP link request is actually listening on port 9090.

Input in browserhttp://localhost:9090

You can see the browser page outputHello astaxie!

Try another address:http://localhost:9090/?url_long=111&url_long=222

What does the browser output and what does the server output?

The output information on the server side is as follows:

Information printed on the server side after the user accesses the web

We see the above code, to write a web server is very simple, just call the two functions of the HTTP package.

Recommended Today

Think about open source project promoting rust search extension: quickly search rust documents in the browser address bar

Open source project name:Rust Search Extension Introduction to open source projects:Quick search for rust documents in the browser address barOpen source project type:teamProject creation time:2020 GitHub data:375 Star,18 ForkGitHub address:https://github.com/huhu/rust-search-extension Rust search extension is a plug-in that can quickly search rust documents, Crites, built-in properties and error codes in the browser address bar. It supports […]