`
qq466862016
  • 浏览: 125697 次
  • 来自: 杭州
社区版块
存档分类
最新评论

golang web 静态资源路由设置

阅读更多
package static


import(
	"fmt"
	"net/http"
	"os"
	"io/ioutil"
	"log"

)


func Start() {
	fmt.Println("init...")
	http.HandleFunc("/static/",doExecute)
	http.ListenAndServe(":8088",nil)
}

var realPath string ="D:/work/software"
func doExecute( response http.ResponseWriter,request *http.Request) {
	
	    requestUrl :=request.URL.String()
	    fmt.Println(requestUrl[:])
		filePath := requestUrl[len("/static"):]
		fmt.Println("requestUrl =",filePath)
		file,err :=os.Open(realPath + filePath)
		defer file.Close()
		if err != nil {
			 log.Println("static resource:", err)
			response.WriteHeader(404)
		} else {
			bs,_ := ioutil.ReadAll(file)
			
			response.Write(bs)
		}
		
		
	
	
	
}

 

package main
import "static"
func main() {
	
	
  static.Start()
}

  在浏览器输入:http://localhost:8088/static/**

** 为static目录下对应映射文件路径

1
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics