Use Golang's standard library to build a website--4. Issues with static resource handling

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Building the site inevitably to use a variety of static resources, this section, to see How to load css,js pictures and so on these resources.

Construct a simple HTML test file on a previous basis

<HTML>    <head>        <title>Hello World</title>        <link href="static/core.css" type="Text/css " Rel="stylesheet" />    </head>    <body>        <div id="header">            <p>The IS header</P>        </div>        <div id="main">            <p>This is main<br />                {{. Name | showname}} </P></div><div id="Footer" ><p>This is footer</P></Div ></body></HTML>                                                     

Then create a CSS file:

*{  font-size: px;  font-weight: bold; }#header {  background-color: red  }#main {  background-color: yellow;} #footer {  background-color: blue;} 

Then run the previous go file with the following results:

From the running results, we'll see that CSS doesn't work, so let's take a look at why:
Let's do a simple test:
We previously registered a route in the Main method:

http.HandleFunc("/", Index)

We expect to be able to go to index.html when we access http://localhost:8080 directly.
Page.
But in fact?
Let's try this. Address:
Http://localhost:8080/core.css
The same get is index.html the content of this page,
Which means that our registered route also matches the/CORE.CSS request.

What is the problem?
We have to write a route function ourselves to see how it matches the route:
Let's take a look at the documentation for go: Look at the declaration of the Listenandserve function:

stringerror

If you want to write the route function, you have to implement handler this interface, declared as follows:

type Handler interface {    ServeHTTP(ResponseWriter, *Request)}

Declare a struct first:

type MyMux struct {    routers map[string]func(http.ResponseWriter,*http.Request)}

To implement the Servehttp method:

http.ResponseWriter, r *http.Request) {    //遍历routers,寻找匹配的path    for path, f := range p.routers {        if r.URL.Path == path {            f(w, r)            return        }    }    "Error: Don't match URL '%s'", r.URL.Path)}

Override the main function:

func main() {    mux := &MyMux{}    make(map[string]func(http.ResponseWriter, *http.Request))    mux.routers["/"] = Index    err := http.ListenAndServe(":8080", mux)    ifnil {        fmt.Println("Error: ", err)    }}

In this case, for each request, the mux.routers is traversed once to find out if there is a matching route.
But obviously, if you use the R.url. Path = = Path "Such a way, is unable to meet the requirements,
Because you have to list every possible path, which is obviously unrealistic, we will then consider using regular expressions to match the routing rules.

We need to re-implement the Servehttp method, but we only need to modify if's judgment condition:
But don't forget to import the regexp regular expression package

if ok, _ :=regexp.MatchString("^""$", r.URL.Path{    f(w, r)    return}

And a new one is a route with regular expressions:

mux.routers["/static/.+"Static

Next, we're going to do a separate processing for the files in the matching static file

func Static(w http.ResponseWriter, r *http.Request) {    fmt.Println("Deal Static: ", r.URL.Path)    w.Header().Set("Content-Type""text/css")    http.ServeFile"." + r.URL.Path)}

Now visit the URL separately from the browser:
http://localhost:8080/
Http://localhost:8080/static/core.css
The discovery has been matched properly.
It's ugly, but don't care so much for the details, just to show it.

When we visit http://localhost:8080/, the browser sends a GET/STATIC/CORE.CSS to the server
Request, the server matches the rule to/static/.+, and then calls the Func static () function, then in the function the
R.url. Path is/STATIC/CORE.CSS, if there are more than one folder in the/static directory, also to R. Url. The value of path
Otherwise, this is not the unfolding instructions.

At this time, when we visit http://localhost:8080/, we will find that the page parsing is normal, the effect is as follows:

Similarly, JS and pictures and other static resources can be handled as described above.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.