當前位置: 首頁>>代碼示例>>Golang>>正文


Golang http.ServeFile函數代碼示例

本文整理匯總了Golang中http.ServeFile函數的典型用法代碼示例。如果您正苦於以下問題:Golang ServeFile函數的具體用法?Golang ServeFile怎麽用?Golang ServeFile使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了ServeFile函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: resourceHandler

func resourceHandler(w http.ResponseWriter, req *http.Request) {
	if req.Method == "GET" {
		log.Printf("Serving up path %s", req.URL.Path)
		if req.URL.Path == "/" {
			log.Printf("...redirecting to [resources/index.html]")
			http.ServeFile(w, req, "resources/index.html")
		} else {
			http.ServeFile(w, req, "resources/"+req.URL.Path)
		}
	} else {
		w.WriteHeader(400)
	}
}
開發者ID:tychofreeman,項目名稱:StoryCards,代碼行數:13,代碼來源:stories.go

示例2: init

func init() {
	fmt.Println("Selog filekkkk")
	http.Handle("/index", http.HandlerFunc(Render))
	http.Handle("/index.ghtml", http.HandlerFunc(RenderGoPagesForbidden))

	http.Handle("/", http.HandlerFunc(func(conn http.ResponseWriter, request *http.Request) {
		if request.URL.Path == "/" {
			defaultPage := "index"
			if strings.TrimSpace(defaultPage) != "" {
				http.Redirect(conn, defaultPage, 307)
			}
			return
		}
		val := "src" + request.URL.Path
		input, err := os.OpenFile(val, os.O_RDONLY, 0666)
		//		input,err := os.Open(val)
		if err != nil {
			conn.WriteHeader(404)
			conn.Write([]byte("<h1>404 Not Found</h1>"))
			return
		}
		s, _ := input.Stat()
		conn.Header.Set("Content-Length", fmt.Sprintf("%d(MISSING)", s.Size))
		//	conn.SetHeader("Content-Type", mime.TypeByExtension(strings.ToLower(path.Ext(val))))
		fmt.Sprintf("%d(MISSING)", s.Size)
		mime.TypeByExtension(strings.ToLower(path.Ext(val)))

		conn.WriteHeader(200)
		http.ServeFile(conn, request, val)
	}))
	http.Handle("/src", http.HandlerFunc(RenderGoPagesForbidden))
	http.Handle("/pages", http.HandlerFunc(RenderGoPagesForbidden))

}
開發者ID:santinopnipa,項目名稱:SUT_gopages,代碼行數:34,代碼來源:handler.go

示例3: Home

func Home(w http.ResponseWriter, r *http.Request) {
	if r.RawURL == "/favicon.ico" {
		return
	}
	fmt.Fprintf(os.Stdout, "%s %s\n", r.Method, r.RawURL)
	http.ServeFile(w, r, "templates/index.html")
}
開發者ID:andrewsmedina,項目名稱:gochat,代碼行數:7,代碼來源:main.go

示例4: main

func main() {
	c := 0
	webl := func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "Hello Avatar")
		log.Printf("Page Visited\n")
	}
	countr := func(w http.ResponseWriter, req *http.Request) {
		c++
		fmt.Fprintf(w, "Hi there<br/>You're visiter #%v", c)
		log.Printf("Countr visited %v times\n", c)
	}
	sfile := func(w http.ResponseWriter, req *http.Request) {
		http.ServeFile(w, req, "test2")
		log.Printf("Served File\n")
	}
	echoUrlInfo := func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "Hi there<br/>The URL you're visiting is made up of these component parts!<br/>Gocode!:<br/>%T<br/>%#v", req, req)
		log.Printf("Hit URL Info page\n")
	}
	http.HandleFunc("/hello", webl)
	http.HandleFunc("/counter", countr)
	http.HandleFunc("/fileTest", sfile)
	http.HandleFunc("/urlInfo", echoUrlInfo)
	err := http.ListenAndServe(":12345", nil)
	if err != nil {
		log.Fatalf("ListenAndServe: ", err.String())
	}
}
開發者ID:Fumon,項目名稱:fugoServer,代碼行數:28,代碼來源:simpleserv.go

示例5: RenderTiles

func RenderTiles(w http.ResponseWriter, req *http.Request) {
	e := os.Remove("svg/test-surface.svg")
	if e != nil {
		os.Stderr.WriteString(e.String() + "\n")
	}

	if CurrentTiling == nil {
		EmptySvg(w, req)
		return
	}

	style := req.FormValue("style")

	image := cairo.NewSurface("svg/test-surface.svg", 72*4, 72*4)
	image.SetSourceRGB(0., 0., 0.)
	image.SetLineWidth(.1)
	image.Translate(72*2., 72*2.)
	image.Scale(4., 4.)
	if style == "edges" {
		image.SetSourceRGBA(0., 0., 0., 1.)
		CurrentTiling.DrawEdges(image)
	} else if style == "plain" {
		CurrentTiling.ColourFaces(image, zellij.OrangeBlueBrush)
	} else {
		CurrentTiling.ColourDebugFaces(image)
		CurrentTiling.DrawDebugEdges(image)
	}

	image.Finish()
	http.ServeFile(w, req, "svg/test-surface.svg")
}
開發者ID:ebering,項目名稱:zellij,代碼行數:31,代碼來源:interactive.go

示例6: FileServer

func FileServer(c *http.Conn, req *http.Request) {
	if req.URL.Path == "/" {
		http.Redirect(c, "index.html", 307)
		return
	} else if strings.HasSuffix(req.URL.Path, "html") {
		data, _ := ioutil.ReadFile(req.URL.Path[1:])
		io.WriteString(c, string(data))
		return
	}
	http.ServeFile(c, req, req.URL.Path[1:])
}
開發者ID:abiosoft,項目名稱:lexicon,代碼行數:11,代碼來源:main.go

示例7: File

func File(w http.ResponseWriter, r *http.Request) {
	fn := *root + r.URL.Path[len(filePrefix):]
	fi, err := os.Stat(fn)
	if err != nil {
		http.Error(w, err.String(), http.StatusNotFound)
		return
	}
	if fi.IsDirectory() {
		serveDirectory(fn, w, r)
		return
	}
	http.ServeFile(w, r, fn)
}
開發者ID:patomphong1990,項目名稱:goPlayer,代碼行數:13,代碼來源:player.go

示例8: serveBin

func serveBin(name string) func(w http.ResponseWriter, req *http.Request) {
	return func(w http.ResponseWriter, req *http.Request) {
		me, _ := os.Readlink("/proc/self/exe")
		d, _ := filepath.Split(me)

		for _, n := range []string{
			filepath.Join(d, name),
			filepath.Join(d, fmt.Sprintf("../%s/%s", name, name)),
		} {
			if fi, _ := os.Lstat(n); fi != nil && fi.IsRegular() {
				http.ServeFile(w, req, n)
			}
		}
	}
}
開發者ID:lht,項目名稱:termite,代碼行數:15,代碼來源:main.go

示例9: ServeHTTP

func (h *CgiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	path := r.URL.Path
	var isCGI bool
	file := filepath.FromSlash(path)
	if len(file) > 0 && os.IsPathSeparator(file[len(file)-1]) {
		file = file[:len(file)-1]
	}
	ext := filepath.Ext(file)
	bin, isCGI := h.LangMap[ext]
	file = filepath.Join(h.Root, file)

	f, e := os.Stat(file)
	if e != nil || f.IsDirectory() {
		if len(h.DefaultApp) > 0 {
			file = h.DefaultApp
		}
		ext := filepath.Ext(file)
		bin, isCGI = h.LangMap[ext]
	}

	if isCGI {
		var cgih cgi.Handler
		if h.UseLangMap {
			cgih = cgi.Handler{
				Path: bin,
				Dir:  h.Root,
				Root: h.Root,
				Args: []string{file},
				Env:  []string{"SCRIPT_FILENAME=" + file},
			}
		} else {
			cgih = cgi.Handler{
				Path: file,
				Root: h.Root,
			}
		}
		cgih.ServeHTTP(w, r)
	} else {
		if (f != nil && f.IsDirectory()) || file == "" {
			tmp := filepath.Join(file, "index.html")
			f, e = os.Stat(tmp)
			if e == nil {
				file = tmp
			}
		}
		http.ServeFile(w, r, file)
	}
}
開發者ID:newblue,項目名稱:go-cgiserver,代碼行數:48,代碼來源:cgiserver.go

示例10: main

func main() {
	flag.Parse()

	// source of unique numbers
	go func() {
		for i := 0; ; i++ {
			uniq <- i
		}
	}()

	// set archChar
	var err os.Error
	archChar, err = build.ArchChar(runtime.GOARCH)
	if err != nil {
		log.Fatal(err)
	}

	// find and serve the go tour files
	t, _, err := build.FindTree(basePkg)
	if err != nil {
		log.Fatalf("Couldn't find tour files: %v", err)
	}
	root := filepath.Join(t.SrcDir(), basePkg)
	root := basePkg
	log.Println("Serving content from", root)
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path == "/favicon.ico" || r.URL.Path == "/" {
			fn := filepath.Join(root, "static", r.URL.Path[1:])
			http.ServeFile(w, r, fn)
			return
		}
		http.Error(w, "not found", 404)
	})
	http.Handle("/static/", http.FileServer(http.Dir(root)))
	http.HandleFunc("/kill", kill)

	// set include path for ld and gc
	pkgDir = t.PkgDir()

	if !strings.HasPrefix(*httpListen, "127.0.0.1") &&
		!strings.HasPrefix(*httpListen, "localhost") {
		log.Print(localhostWarning)
	}

	log.Printf("Serving at http://%s/", *httpListen)
	log.Fatal(http.ListenAndServe(*httpListen, nil))
}
開發者ID:k001,項目名稱:Golang-spanish-documentation,代碼行數:47,代碼來源:local.go

示例11: EmbellishFrame

func EmbellishFrame(w http.ResponseWriter, req *http.Request) {
	e := os.Remove("svg/embellishment.svg")
	if e != nil {
		os.Stderr.WriteString(e.String() + "\n")
	}
	frame := quadratic.NewMap()
	jsonErr := json.NewDecoder(strings.NewReader(req.FormValue("frame"))).Decode(frame)
	if jsonErr != nil {
		os.Stderr.WriteString("json error: " + jsonErr.String() + "\n")
		return
	}
	zig, err := zellij.Embellish(frame, MotifDatabase)
	if err != nil {
		os.Stderr.WriteString(err.String() + "\n")
		return
	}
	fmt.Fprintf(os.Stderr, "embellishment has %v faces\n", zig.Faces.Len())
	bx := zig.Verticies.At(0).(*quadratic.Vertex).Point
	tx := zig.Verticies.At(0).(*quadratic.Vertex).Point
	by := zig.Verticies.At(0).(*quadratic.Vertex).Point
	ty := zig.Verticies.At(0).(*quadratic.Vertex).Point
	for i := 1; i < zig.Verticies.Len(); i++ {
		v := zig.Verticies.At(i).(*quadratic.Vertex).Point
		if v.Y().Float64() < by.Y().Float64() {
			by = v
		} else if v.Y().Float64() > ty.Y().Float64() {
			ty = v
		}
		if v.X().Float64() < bx.X().Float64() {
			bx = v
		} else if v.X().Float64() > tx.X().Float64() {
			tx = v
		}
	}
	xwidth := math.Floor(tx.X().Float64() - bx.X().Float64() + 20.0)
	ywidth := math.Floor(ty.Y().Float64() - by.Y().Float64() + 20.0)

	image := cairo.NewSurface("svg/embellishment.svg", xwidth*4, ywidth*4)
	image.SetSourceRGB(0., 0., 0.)
	image.SetLineWidth(.1)
	image.Translate(-bx.X().Float64()*4.+40, -by.Y().Float64()*4.+40)
	image.Scale(4., 4.)
	zig.ColourFaces(image, zellij.OrangeBlueBrush)
	image.Finish()
	http.ServeFile(w, req, "svg/embellishment.svg")
}
開發者ID:ebering,項目名稱:zellij,代碼行數:46,代碼來源:interactive.go

示例12: Redirect

func Redirect(w http.ResponseWriter, r *http.Request) {
	key := r.URL.Path[1:]

	if key == "favicon.ico" {
		http.NotFound(w, r)
	} else if key == "" {
		logo := &Title{Logo: "You.RL"}
		tpl, _ := template.ParseFile("index.html", nil)
		tpl.Execute(w, logo)
	} else if key == "index.js" {
		http.ServeFile(w, r, "index.js")
	} else {
		var url string
		store.Get(&key, &url)
		http.Redirect(w, r, url, http.StatusFound)
	}
}
開發者ID:kenu,項目名稱:You.RL,代碼行數:17,代碼來源:main.go

示例13: DrawSkel

func DrawSkel(w http.ResponseWriter, req *http.Request) {
	e := os.Remove("svg/test-surface.svg")
	if e != nil {
		os.Stderr.WriteString(e.String() + "\n")
	}
	skeleton := req.FormValue("skeleton")
	image := cairo.NewSurface("svg/test-surface.svg", 72*4, 72*4)
	image.SetSourceRGB(0., 0., 0.)
	image.SetLineWidth(.1)
	image.Translate(72*2., 72*2.)
	image.Scale(4., 4.)
	skel, ok := zellij.SkeletonMap(skeleton)
	if ok != nil {
		os.Stderr.WriteString(ok.String() + "\n")
	}
	skel.DrawEdges(image)
	image.Finish()
	http.ServeFile(w, req, "svg/test-surface.svg")
}
開發者ID:ebering,項目名稱:zellij,代碼行數:19,代碼來源:interactive.go

示例14: httpHandler

func httpHandler(c *http.Conn, req *http.Request) {
	path := req.URL.Path

	//try to serve a static file
	if strings.HasPrefix(path, "/static/") {
		staticFile := path[8:]
		if len(staticFile) > 0 {
			http.ServeFile(c, req, "static/"+staticFile)
			return
		}
	}

	req.ParseForm()
	resp := routeHandler((*Request)(req))
	c.WriteHeader(resp.StatusCode)
	if resp.Body != nil {
		body, _ := ioutil.ReadAll(resp.Body)
		c.Write(body)
	}
}
開發者ID:tjweir,項目名稱:web.go,代碼行數:20,代碼來源:web.go

示例15: StaticFile

// Server static files, like CSS and JS directly
func StaticFile(response http.ResponseWriter, request *http.Request) {
	url := request.URL.Path

	// remove the beginning slash so we don't look in the FS root for the file
	if url[0] == '/' {
		url = url[1:]
	}

	if strings.Contains(url, "../") {
		log.Println("Attempt to traverse outside of static folders.")
		http.Error(response, "Stop it.", http.StatusInternalServerError)
		return
	}

	// Log that a static file was served
	log.Print("Serving static file ", url)

	// serve the file
	http.ServeFile(response, request, url)
}
開發者ID:natelong,項目名稱:smushfile,代碼行數:21,代碼來源:smushfile.go


注:本文中的http.ServeFile函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。