Advertisement
Pug_coder

download

Oct 8th, 2021
509
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.50 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "github.com/mgutz/logxi/v1"
  5.     "html/template"
  6.     "net/http"
  7. )
  8.  
  9. const INDEX_HTML = `
  10.     <!doctype html>
  11.     <html lang="ru">
  12.         <head>
  13.             <meta charset="utf-8">
  14.             <title>Последние новости с citilink.ru</title>
  15.         </head>
  16.         <body>
  17.             {{if .}}
  18.                 {{range .}}
  19.                     <a href="https://www.citilink.ru/catalog/processory/{{.Ref}}">{{.Title}}</a>
  20.                     <span>{{.Price}} рублей</span>
  21.                     <br/>
  22.                 {{end}}
  23.             {{else}}
  24.                 Не удалось загрузить новости!
  25.             {{end}}
  26.         </body>
  27.     </html>
  28.     `
  29.  
  30. var indexHtml = template.Must(template.New("index").Parse(INDEX_HTML))
  31.  
  32. func serveClient(response http.ResponseWriter, request *http.Request) {
  33.     path := request.URL.Path
  34.     log.Info("got request", "Method", request.Method, "Path", path)
  35.     if path != "/" && path != "/index.html" {
  36.         log.Error("invalid path", "Path", path)
  37.         response.WriteHeader(http.StatusNotFound)
  38.     } else if err := indexHtml.Execute(response, downloadNews()); err != nil {
  39.         log.Error("HTML creation failed", "error", err)
  40.     } else {
  41.         log.Info("response sent to client successfully")
  42.     }
  43. }
  44.  
  45. func main() {
  46.     http.HandleFunc("/", serveClient)
  47.     log.Info("starting listener")
  48.     log.Error("listener failed", "error", http.ListenAndServe("127.0.0.1:6060", nil))
  49. }
  50.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement