Friday, 30 October 2020

go web app 13 static files

 
click file icon will open vehicle picture

//tutorial.go
package main

import (
"html/template"
"net/http"

"github.com/gorilla/mux"
)

type car struct {
Color   string
Mileage int
Model   string
}

var templates *template.Template

//var colors = []string{"red", "green", "blue"}

var truck = car{
Color:   "black",
Mileage: 12345,
Model:   "F-150",
}

var sedan = car{
Color:   "white",
Mileage: 321,
Model:   "Corolla",
}


func indexGetHandler(w http.ResponseWriter, r *http.Request) {
templates.ExecuteTemplate(w, "index.html", []car{truck, sedan})
}

func main() {
templates = template.Must(template.ParseGlob("templates/*.html"))
r := mux.NewRouter()
r.HandleFunc("/", indexGetHandler).Methods("GET")
fs := http.FileServer(http.Dir("./static/"))
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", fs))
http.Handle("/", r)
http.ListenAndServe(":8000", nil)
}

----------------------
//templates/index.html
<html>

<head>
    <title> Templates</title>
    <link rel="stylesheet" type="text/css" href="/static/index.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>

<body>
    <h1>Cars</h1>

    <ul>
        {{range .}}
        <li>{{.Color}} {{.Model}} - {{.Mileage}} Miles
            <i class="fa fa-file" onclick="window.open('http://localhost:8000/static/{{.Model}}.jpg','_blank')"></i>
        </li>
        {{end}}
    </ul>
</body>

</html>

-----------------------------
//static/index.css
body > ul {
    padding : 0.5em;
    width: 200px;
    margin: 1em 0em;
    background:#ccc;
    border: 1px solid rgb(202, 48, 48);
}

i{
    cursor: pointer;
}

reference:

No comments:

Post a Comment