Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
4.2 kB
1
Indexable
Never
package main

import (
	"fmt"
	"log"
	"net/http"
	"path/filepath"
	"strconv"

	"github.com/go-chi/chi/v5"
	"github.com/go-chi/chi/v5/middleware"
	"gitlab.com/CristiDeac/website/controllers"
	"gitlab.com/CristiDeac/website/views"
)

type User struct {
	Name       string
	Age        int
	Meta       UserMeta
	Address    UserAddress
	Contacts   map[string]string
	Membership string
}

type UserMeta struct {
	Visits int
}

type UserAddress struct {
	City    string
	Country string
}

type Gallery struct {
	ID   int64
	Name string
}

func executeTemplate(w http.ResponseWriter, filepath string, data interface{}) {
	t, err := views.Parse(filepath)
	if err != nil {
		log.Printf("parsing template: %v", err)
		http.Error(w, "There was an error parsing the template.", http.StatusInternalServerError)
		return
	}
	t.Execute(w, data)
}

func homeHandler(w http.ResponseWriter, r *http.Request) {
	tplPath := filepath.Join("templates", "home.gohtml")
	user := User{
		Name:       "Andrei",
		Age:        22,
		Meta:       UserMeta{Visits: 4},
		Address:    UserAddress{City: "Sighisoara", Country: "Romania"},
		Contacts:   map[string]string{"email": "andrei@gmail.com", "phone number": "0987654321"},
		Membership: "premium",
	}
	executeTemplate(w, tplPath, user)
}

func notFoundHandler(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusNotFound)
	executeTemplate(w, filepath.Join("templates", "notfound.gohtml"), nil)
}

func faqHandler(w http.ResponseWriter, r *http.Request) {
	tplPath := filepath.Join("templates", "faq.gohtml")
	executeTemplate(w, tplPath, nil)
}

func galleryHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	galleryID := chi.URLParam(r, "id")

	id, err := strconv.ParseInt(galleryID, 10, 64)
	if err != nil {
		log.Printf("Error converting id parameter: %v", err)
		http.Error(w, "Gallery ID is invalid", http.StatusBadRequest)
	}

	gallery := Gallery{
		ID:   id,
		Name: "Nume Galerie",
	}
	tplPath := filepath.Join("templates", "gallery.gohtml")
	executeTemplate(w, tplPath, gallery)
}

func main() {
	r := chi.NewRouter()
	r.Use(middleware.Logger)
	r.Get("/", homeHandler)

	r.Get("/contact", controllers.StaticHandler(
		views.Must(views.Parse(filepath.Join("templates", "contact.gohtml")))))
	r.Get("/faq", faqHandler)
	r.With(middleware.Logger).Get("/gallery/{id}", galleryHandler)
	r.NotFound(notFoundHandler)

	fmt.Println("Starting the server on :3000...")
	err := http.ListenAndServe(":3000", r)
	if err != nil {
		log.Fatalf("Server failed to start: %v", err)
	}
}

package views

import (
	"fmt"
	"html/template"
	"log"
	"net/http"
)

func Must(t Template, err error) Template {
	if err != nil {
		panic(err)
	}
	return t
}

func Parse(filepath string) (Template, error) {
	tpl, err := template.ParseFiles(filepath)
	if err != nil {
		return Template{}, fmt.Errorf("parsing template : %w", err)
	}
	return Template{
		htmlTpl: tpl,
	}, nil
}

type Template struct {
	htmlTpl *template.Template
}

func (t Template) Execute(w http.ResponseWriter, data interface{}) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	err := t.htmlTpl.Execute(w, data)
	if err != nil {
		log.Printf("executing template: %v", err)
		http.Error(w, "There was an error executing the template.", http.StatusInternalServerError)
		return
	}
}

package controllers

import (
	"net/http"

	"gitlab.com/CristiDeac/website/views"
)

func StaticHandler(tpl views.Template) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		tpl.Execute(w, nil)
	}
}

<h1>Welcome to my site {{.Name}}</h1>
<p> Age: {{.Age}}</p>
<p> Visits: {{.Meta.Visits}}</p>
<p> City: {{.Address.City}}</p>
<p> Country: {{.Address.Country}}</p>
<p> Contacts:</p> 
<ul> 
    {{range $key, $value := .Contacts}}
    <li>{{$key}}: {{$value}}</li> 
    {{end}}
</ul> 
<div>
    {{if eq .Membership "premium"}}
        <p>Thank you! You are a premium member!</p>
    {{else if eq .Membership "normal"}}
        <p>You are a normal member, consider upgrading to premium for more benefits!</p>
    {{else}}
        <p>You are not a member!</p> 
    {{end}}
</div>
        

Leave a Comment