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目录下对应映射文件路径

猜你喜欢

转载自qq466862016.iteye.com/blog/2274323
今日推荐