The example in this article describes the Golang method for implementing HTTP server processing static files. Share to everyone for your reference, specific as follows:
The new version is more streamlined:
Copy Code code as follows:
Package Main
Import (
"Flag"
"Log"
"Net/http"
"OS"
"IO"
"Path"
"StrConv"
)
var dir string
var Port int
var Statichandler http. Handler
Initialization parameters
Func init () {
dir = path. Dir (OS. Args[0])
Flag. Intvar (&port, "Port", 80, "Server port")
Flag. Parse ()
Statichandler = http. Fileserver (http. Dir (dir))
}
Func Main () {
http. Handlefunc ("/", Staticserver)
ERR: = http. Listenandserve (":" +strconv. Itoa (port), nil)
If Err!= nil {
Log. Fatal ("Listenandserve:", err)
}
}
Static file Handling
Func staticserver (w http. Responsewriter, req *http. Request) {
If req. Url. Path!= "/" {
Statichandler.servehttp (W, req)
Return
}
Io. WriteString (W, "Hello, world!\n")
}
Old version:
Copy Code code as follows:
Package Main
Import (
"Flag"
"Log"
"Net/http"
"OS"
"Path"
"StrConv"
)
var dir string
var Port int
var Indexs []string
Initialization parameters
Func init () {
dir = path. Dir (OS. Args[0])
Flag. Intvar (&port, "Port", 80, "Server port")
Flag. Parse ()
Indexs = []string{"index.html", "index.htm"}
}
Func Main () {
http. Handlefunc ("/", Staticserver)
ERR: = http. Listenandserve (":" +strconv. Itoa (port), nil)
If Err!= nil {
Log. Fatal ("Listenandserve:", err)
}
}
Static file Handling
Func staticserver (w http. Responsewriter, req *http. Request) {
File: = dir + req. Url. Path
FI, err: = OS. Stat (file)
If OS. Isnotexist (Err) {
http. NotFound (W, req)
Return
}
If Err!= nil {
http. Error (W, err.) Error (), 500)
Return
}
If Fi. Isdir () {
If req. Url. Path[len (req. Url. Path)-1]!= '/' {
http. Redirect (W, req, req). Url. path+ "/", 301)
Return
}
For _, Index: = Range Indexs {
FI, err = os. Stat (file + index)
If Err!= nil {
Continue
}
http. Servefile (W, req, File+index)
Return
}
http. NotFound (W, req)
Return
}
http. Servefile (W, req, file)
}
I hope this article will help you with your go language program.