Golang Web Server Using Gorilla Package - Golang Web Development
In this Golang Web Development Series #8, we will learn how to create a Golang web server using Gorilla Mux, Handlers, CSRF packages with step by step guide here in Golang's Web Development Series.
Get Linode Account:
https://www.linode.com/?r=6aae17162e9af054062c47ab53e14e517b380516
Maharlikans Code Github:
https://github.com/maharlikanscode/golang-web-development-series
#MaharlikansCode
#GolangWebDevelopment8
#GolangWebServer
#GolangTutorial
#LearnGolangWebDevelopment
#Golang
#LifeAsSoftwareDeveloper
#Maharlikans
#FilipinoSoftwareDeveloper
If you go with extra mile for buying me a cup of coffee, I appreciate it guys: https://ko-fi.com/maharlikanscode
Source Codes:
main.go:
package main
import (
"context"
"flag"
"fmt"
"gowebapp/api"
"gowebapp/config"
"net/http"
"os"
"os/signal"
"time"
"github.com/gorilla/csrf"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/itrepablik/itrlog"
"github.com/itrepablik/sakto"
)
var CurrentLocalTime = sakto.GetCurDT(time.Now(), "Asia/Manila")
func main() {
os.Setenv("TZ", config.SiteTimeZone) // Set the local timezone globally
fmt.Println("Starting the web servers at ", CurrentLocalTime)
var dir string
var wait time.Duration
flag.DurationVar(&wait, "graceful-timeout", time.Second*15, "the duration for which the server gracefully wait for existing connections to finish - e.g. 15s or 1m")
flag.StringVar(&dir, "dir", "static", "the directory to serve files from. Defaults to the current dir")
flag.Parse()
r := mux.NewRouter()
csrfMiddleware := csrf.Protect(
[]byte(config.SecretKeyCORS),
csrf.TrustedOrigins([]string{config.SiteDomainName}),
)
// This is related to the CORS config to allow all origins []string{"*"} or specify only allowed IP or hostname.
cors := handlers.CORS(
handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type", "Authorization"}),
handlers.AllowedMethods([]string{"GET", "POST", "PUT", "HEAD", "OPTIONS"}),
handlers.AllowedOrigins([]string{config.SiteDomainName}),
)
r.Use(cors)
r.Use(csrfMiddleware)
r.Use(loggingMiddleware)
r.Use(mux.CORSMethodMiddleware(r))
// This will serve the files under http://localhost:8000/static/filename
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir))))
// Initialize the APIs here
api.MainRouters(r) // URLs for the main app.
srv := &http.Server{
Addr: "127.0.0.1:8081",
// Good practice to set timeouts to avoid Slowloris attacks.
WriteTimeout: time.Second * 15,
ReadTimeout: time.Second * 15,
IdleTimeout: time.Second * 60,
Handler: r, // Pass our instance of gorilla/mux in.
}
// Run our server in a goroutine so that it doesn't block.
go func() {
msg := `Web server started at `
fmt.Println(msg, CurrentLocalTime)
itrlog.Info("Web server started at ", CurrentLocalTime)
if err := srv.ListenAndServe(); err != nil {
itrlog.Error(err)
}
}() // Note the parentheses - must call the function.
// BUFFERED CHANNELS = QUEUES
c := make(chan os.Signal, 1) // Queue with a capacity of 1.
// We'll accept graceful shutdowns when quit via SIGINT (Ctrl+C)
// SIGKILL, SIGQUIT or SIGTERM (Ctrl+/) will not be caught.
signal.Notify(c, os.Interrupt)
// Block until we receive our signal.
lt-c
// Create a deadline to wait for.
ctx, cancel := context.WithTimeout(context.Background(), wait)
defer cancel()
srv.Shutdown(ctx)
fmt.Println("Shutdown web server at " + CurrentLocalTime.String())
itrlog.Warn("Server has been shutdown at ", CurrentLocalTime.String())
os.Exit(0)
}
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Do stuff here
req := "IP:" + sakto.GetIP(r) + ":" + r.RequestURI + ":" + CurrentLocalTime.String()
fmt.Println(req)
itrlog.Info(req)
// Call the next handler, which can be another middleware in the chain, or the final handler.
next.ServeHTTP(w, r)
})
}
api/main_routers.go:
package api
import (
"gowebapp/config"
"html/template"
"net/http"
"github.com/gorilla/csrf"
"github.com/gorilla/mux"
)
// MainRouters are the collection of all URLs for the Main App.
func MainRouters(r *mux.Router) {
r.HandleFunc("/", Home).Methods("GET")
}
// contextData are the most widely use common variables for each pages to load.
type contextData map[string]interface{}
// Home function is to render the homepage page.
func Home(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.ParseFiles(config.SiteRootTemplate+"front/index.html", config.SiteHeaderTemplate, config.SiteFooterTemplate))
data := contextData{
"PageTitle": "Welcome to Maharlikans Code Tutorial Series",
"PageMetaDesc": config.SiteSlogan,
"CanonicalURL": r.RequestURI,
"CsrfToken": csrf.Token(r),
"Settings": config.SiteSettings,
}
tmpl.Execute(w, data)
}
Видео Golang Web Server Using Gorilla Package - Golang Web Development автора PHP и Unit-тестирование
Видео Golang Web Server Using Gorilla Package - Golang Web Development автора PHP и Unit-тестирование
Информация
1 декабря 2023 г. 13:43:50
00:45:59
Похожие видео