0

Всем доброго дня. Решил тут попробовать сделать web-сервер на Go. В отдельном файле лежат данные в JSON формате, и по идее они должны выводиться на страницу.

Иерархия проекта

Но вместо этого выводится только рамка. Прошу помочь/подсказать, где ошибка.

main.go

    package main 
    import (
        "html/template"
        "log"
        "net/http"
    )
var tpl template.Template func init() { tpl = template.Must(template.ParseGlob("templates/.html")) }

func main() {
    http.HandleFunc("/", indexPage)
    log.Fatal(http.ListenAndServe(":8000", nil))
}

func indexPage(w http.ResponseWriter, r *http.Request) {
    err := tpl.Execute(w, "index.html")
    if err != nil {
        log.Fatalln(err)
    }
}

index.html

<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> <style> .cards { border: 1px solid red; display: flex; justify-content: space-between; padding: 20px; } .card { border: 1px solid blue; padding: 5px; width: 100%; } .card__id { font-weight: bold; } .card__name { font-style: italic; } </style> </head> <body> <div class="cards"> </div> <script> function card({ id, name }) { return ` <div class="card"> <div class="card__id">${id}</div> <div class="card__name">${name}</div> </div> `; }; const container = document.querySelector('.cards'); window.container = container; fetch('/api/users.json') .then(users => users.json()) .then(users => { container.innerHTML = users.map(card).join(''); }); </script> </body> </html>

JSON файл, из которого берутся данные:

[ { "id": 1, "name": "Олег" }, { "id": 2, "name": "Мария" }, { "id": 3, "name": "Афанасий" } ]

1
  • Откройте консоль разработчика в браузере и посмотрите как выглядит итоговая html страница вместе с JS-скриптом.
    – Mike
    13 мая 2018 в 15:18

1 ответ 1

0

Добавил еще один handler в main. Полёт нормальный

func main() {
http.HandleFunc("/", indexPage)
http.HandleFunc("/api/users.json", func(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, r.URL.Path[1:])
})
log.Fatal(http.ListenAndServe(":8000", nil))
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.