Go language static Server
Learning the Go language is not necessarily accurate.
In case of war, JAVA generally acts as an aircraft carrier battle group.
Once dispatched, it will be frigates, cruisers, aircraft carriers, early warning aircraft, e-warfare aircraft, and submarine.
So powerful that we can kill the past.
(JVM, dozens of JAR packages, Tomcat middleware, SSH framework, various configuration files... are inherently heavyweight, designed for large-scale combat)
The GO language is more like The F35 combat bomber.
One-click, quietly, drop a bomb and leave.
Exclusive bomber, air combat will also be a little bit.
It's just like F22.
(GO is a compiled language that does not require dependency or virtual machines. It can call C Code and is simple enough, but comprehensive)
Knowledge points for planning Go Language Learning
1. Build an Http service
2. Connect to the database
3. Local IO
4. Multithreading
5. Network
6. Call local commands
7. Call the C language code
First, build a static Server
I like to use HTML to send JSON requests to the backend for processing through AJAX.
HttpServer. go
Package main
Import (
"Flag"
"Io/ioutil"
"Log"
"Net/http"
"OS"
"Strings"
)
Var realPath * string
Func staticResource (w http. ResponseWriter, r * http. Request ){
Path: = r. URL. Path
Request_type: = path [strings. LastIndex (path, "."):]
Switch request_type {
Case ". css ":
W. Header (). Set ("content-type", "text/css ")
Case ". js ":
W. Header (). Set ("content-type", "text/javascript ")
Default:
}
Fin, err: = OS. Open (* realPath + path)
Defer fin. Close ()
If err! = Nil {
Log. Fatal ("static resource:", err)
}
Fd, _: = ioutil. ReadAll (fin)
W. Write (fd)
}
Func main (){
RealPath = flag. String ("path", "", "static resource path ")
Flag. Parse ()
Http. HandleFunc ("/", staticResource)
Err: = http. ListenAndServe (": 8080", nil)
If err! = Nil {
Log. Fatal ("ListenAndServe:", err)
}
}
See a more BT method on the internet ..
Package main
Import (
"Net/http"
)
Func main (){
Http. Handle ("/", http. FileServer (http. Dir ("/tmp/static /")))
Http. ListenAndServe (": 8080", nil)
}
Decompress the EasyUI front-end framework to the/tmp/static directory.
Run
Go run HttpServer. go -- path =/tmp/static
Check the webpage. Everything works.
In this way, the Go language implements a simple static server with less than 50 lines of code and less than 7 MB of executable files after compilation.
Install Go Language Pack in Ubuntu
Go language programming (HD) full-version ebook
Go language and beauty-surpassing "Hello World"
Why do I like the Go language?
Implementation of the Go language memory distributor
Go language international support (based on gettext-go)
This article permanently updates the link address: