golang搭建静态web服务器的实现方法

æè¡æ±ä¸ååæ¥å¦ã好ä¹æ²¡åæäºï¼ä¸ºä¿æå¹³å°ä¸çæ´»è·åº¦ï¼æä»å¤©å°±å享ä¸ä¸ªåå­¦å°çç¥è¯ï¼ä½¿ç¨golangæ­å»ºéæwebæå¡å¨ï¼äº²æµå¯ç¨ï¼é代ç ï¼

使ç¨è¿golang语è¨çç¨åºç¿é½åºè¯¥ç¥éï¼å¨ä½¿ç¨golangå¼åçæ¶åï¼æ们æ¯ä¸éè¦è¯¸å¦iis,apache,nginx,kangleç­æå¡å¨æ¯æçã

为ä»ä¹å¢ï¼

åå æ¯ï¼golangçnet/httpå中已ç»æä¾äºHTTPç客æ·ç«¯ä¸æå¡ç«¯å®ç°æ¹æ¡ã

ç½ä¸è¨è®ºé½è¯´golangä¸éååwebå¼åï¼ç¸å¯¹phpãjavaã.netãnodejsç­åç±»å端语è¨æ¥è¯´ï¼ä½¿ç¨golangæ¥åwebå¼åï¼ç¡®å®æ¯ä¸ä¸ªå¤§å·¥ç¨ã

æ¨ææ°å¥½çå°ä¸ç¯å³äºä½¿ç¨golangæ­å»ºwebæå¡å¨çæç« ï¼å¿çé¾èï¼äºæ¯èªå·±ä¹æè¾äºä¸ä¸ï¼ç¨æ¥ç»ç»æã

ææ¯æ°æä¸è·¯ï¼ç§æ¬æç« éçå容ï¼æ»æ¯ç£ç£ç¢°ç¢°ï¼æ¯æ¬¡è¿è¡é½æ¯æ¾ä¸å°è·¯å¾ã代ç æ¯è¿æ ·çï¼

func main() {
 http.Handle("/css/", http.FileServer(http.Dir("template")))
 http.Handle("/js/", http.FileServer(http.Dir("template")))

 http.ListenAndServe(":8080", nil)
}

ç®å½ç»æï¼

src
|--main
| |-main.go
|--template
| |-css
|  |--admin.css
| |-js
|  |--admin.js
| |-html
|  |--404.html

以ä¸è¿è¡ç»ææ¯ï¼æ¾ä¸å°templateè¿ä¸ªè·¯å¾ã

å¶å®æå¾çº³é·ï¼æç« ä½èé½å¯ä»¥æåè¿è¡èµ·æ¥è¿ä¸ªdemoï¼æä¹å°æè¿éï¼å°±å¯å¨ä¸æ¥äºå¢ï¼

é£ä¹é®é¢æ¥äºï¼

1.æ¯ä»ä¹åå å¯¼è´ç¨åºèµ·ä¸æ¥å¢ï¼
2.http.Dir()æåçæ¯ä»ä¹è·¯å¾ï¼

äºæ¯æ追踪æ¥å¿ï¼å¦ä¸

2018/01/07 11:09:28 open template/html/404.html: The system cannot find the path specified.

åç°é®é¢æ¯åºå¨æ¾ä¸å°è·¯å¾ä¸ã解å³äºç¬¬ä¸ä¸ªé®é¢åï¼é£ä¹æ¥ä¸æ¥å°±éè¦ææç½http.Dir()å°åºæåçæ¯åªä¸ªè·¯å¾ã

ææ¥çäºå®æ¹ä¾å­ï¼

log.Fatal(http.ListenAndServe(":8080", http.FileServer(http.Dir("/usr/share/doc"))))

ä»ä¸é¢ä¾å­http.Dir("/usr/share/doc")å¯çåºï¼è¯¥è·¯å¾æåçæ¯linuxç³»ç»éçç»å¯¹è·¯å¾ãé£ä¹é®é¢å°±è§£å³äºï¼æåªéè¦å°http.Dir()çè·¯å¾æ¹ä¸ºè¿è¡æ¶çç¸å¯¹è·¯å¾ï¼æè使ç¨ç»å¯¹è·¯å¾å°±å¯ä»¥äºã

å¦ä¸ä¸ªä¾å­ï¼ä½¿ç¨http.StripPrefix()æ¹æ³ï¼

// To serve a directory on disk (/tmp) under an alternate URL
// path (/tmpfiles/), use StripPrefix to modify the request
// URL's path before the FileServer sees it:
http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))

å¯çåºï¼tmpfilesæ¯tmpç®å½ä¸çä¸ä¸ªå­ç®å½ã

æ¢ç¶é®é¢é½è§£å³äºï¼é£ä¹å°±ä¿®æ¹ä¸ä¸ä»£ç ï¼éæ°è¿è¡

func Template_dir() string {
 template_dir := "E:\\project\\gotest\\src\\template"
 return template_dir
}

func main() {
 http.Handle("/css/", http.FileServer(http.Dir(Template_dir())))
 http.Handle("/js/", http.FileServer(http.Dir(Template_dir())))

 http.ListenAndServe(":8080", nil)
}

ç¼è¯è¿è¡åï¼å¨æµè§å¨ä¸­è¾å¥localhost:8080/css/ï¼å¯æåçå°template/css/ç®å½ä¸çadmin.cssæ件ã

以ä¸å°±æ¯æ¬æçå¨é¨å容ï¼å¸æ对大家ç学习ææ帮å©ï¼ä¹å¸æ大家å¤å¤æ¯æèæ¬ä¹å®¶ã

相关推荐