Golang 开发web应用时的静态文件处理方法(v0.01)

yavobo · · 3936 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

一、首先,我的应用目录结构如下图:

分析一下:应用运行文件所在文件夹在hw,此即为应用根目录。模板则位于hw/template中,其中css文件在其中的css文件夹,javascript文件在js文件夹。

应用在hw文件夹中被执行,运行过程中需要读取template/css/main.css文件及template/js中的javascript文件。

二、需要用到如下的包:"net/http"

    涉及到的函数:http.Fileserver,http.StripPrefix,http.Handle。

    1、http.FileServer

     func FileServer(root FileSystem) Handler


    FileServer returns a handler that serves HTTP requests with the contents of the file system rooted at root.
    To use the operating system's file system implementation, use http.Dir:
    http.Handle("/", http.FileServer(http.Dir("/tmp")))

    2、http.StripPrefix

     func StripPrefix(prefix string, h Handler) Handler


    StripPrefix returns a handler that serves HTTP requests by removing the given prefix from the request URL's Path and invoking the handler h.

    StripPrefix handles a request for a path that doesn't begin with prefix by replying with an HTTP 404 not found error.

     3、http.Handle

    func Handle(pattern string, handler Handler)
    Handle registers the handler for the given pattern in the DefaultServeMux. The
    documentation for ServeMux explains how patterns are matched.
    func HandleFunc
    func HandleFunc(pattern string, handler func(ResponseWriter,
    *Request))
    HandleFunc registers the handler function for the given pattern in the
    DefaultServeMux. The documentation for ServeMux explains how patterns are
    matched.
    func ListenAndServe
    func ListenAndServe(addr string, handler Handler) error
    ListenAndServe listens on the TCP network address addr and then calls Serve with
    handler to handle requests on incoming connections. Handler is typically nil, in which
    case the DefaultServeMux is used.

三、实例代码

1、hw.go

package main

import (
	"io"
	"log"
	"net/http"
)

func Hello(w http.ResponseWriter, r *http.Request) {
	hp := `<html>
    <head>
    <title>okkkkkk</title>
    <link rel="stylesheet" href="template/css/main.css" type="text/css" /> 
    </head>
    <body>
        <h2>this is a test for golang.</h2>
    </body>
    </html>`
	io.WriteString(w, hp)
}

func StaticServer(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("content-type", "text/html")
	staticHandler := http.FileServer(http.Dir("./template/"))
	staticHandler.ServeHTTP(w, r)
	return
}

func main() {
	http.Handle("/template/", http.StripPrefix("/template/", http.FileServer(http.Dir("./template"))))
	http.HandleFunc("/", Hello)
	err := http.ListenAndServe(":8000", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err.Error())
	}
}

2、main.css

body
{
    background-color: black;
    color: red;
}

关键在:http.Handle("/template/", http.StripPrefix("/template/", http.FileServer(http.Dir("./template")))) 这一行代码中实现了静态文件的共享。

主要情况为:

a、网站根目录:http:/127.0.0.1:8000/

b、需要读取的css文件为:http://127.0.0.1:8000/template/css/main.css,注意其中的 /template与http.Handle("/template/"...中的template对应。

四、运行效果



有疑问加站长微信联系(非本文作者)

本文来自:CSDN博客

感谢作者:yavobo

查看原文:Golang 开发web应用时的静态文件处理方法(v0.01)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

3936 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传