Create a web server in Go language (net/http) (2)

It's been a long time since the last article. The previous article was here In this article, I will try to display the html file by http communication with golang.

There are many explanations. Now that I understand the sample code myself, I hope I can share it with you. I look forward to working with you.

This article is not very informative. The author himself does not think it is a very good article. I wrote it as a record.

This source code can be found in the book "Web Application Development in Go".

package main

import (
	"log"
	"net/http"

	//add to
	"path/filepath"
	"sync"
	"text/template"
)

type templateHandler struct {
	once     sync.Once
	filename string
	templ *template.Template
}


func (t *templateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	t.once.Do(func() {
		t.templ = template.Must(template.ParseFiles(filepath.Join("templates", t.filename)))
	})

	t.templ.Execute(w, nil)
}

func main() {
	http.Handle("/", &templateHandler{filename: "template1.html"})
	log.Fatal(http.ListenAndServe(":8080", nil))
}

The import part has increased compared to the previous time. It's a rough sketch, but I'll explain it.

path/filepath ・ ・ ・ Manipulate the file path. This allows you to connect and specify paths.

sync ... Required to define a function that executes only once. This time, I want to read the html file at once, so I will use this package.

text/template ・ ・ ・ Used to handle html. If'prth/filepath'introduced at the beginning is a path operation, this package actually reads the file specified by that path as a web page.

type templateHandler struct {
	//To use a function that runs only once
	once     sync.Once
	filename string
	//Use Template with pointer
	templ *template.Template
}

First of all, define the structure. Create a function to be executed only once using the package sync imported here, a filename to decide which file to display, and a template to actually display the html file with pointers.

Next, add a method (function) to the structure. When adding a method to a structure, add it according to the following rules.

func(Arbitrary variable,Structure name(Pointer))Method name(argument){

} 

Any variable part can determine what variable the structure itself is represented in the function to be added. It's hard to understand at once, so I'll understand it as I read the source code.

func (t *templateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	t.once.Do(func() {
		t.templ = template.Must(template.ParseFiles(filepath.Join("templates", t.filename)))
	})

	t.templ.Execute(w, nil)
}

Now let's read the added method. The "func handler" explained in Last time has been added with the name "ServeHTTP". However, this time it is a little different from the last time, and I will use the structure declared with the name once. We will create a function to be executed only once using the method "Do" in once. that is

func(){
     t.tmpl = template.Must(template.ParseFiles(filepath.Join("templates", t.filename))
   })
   t.templ.Execute(w, nil)
}

This is the part. Access tmpl in the structure templeHandler with t.tmpl. When adding a method, it is (t, * templeHandler), so it is "t". If you change this to "s", access it with s.tmpl.

Set template.Must to run absolutely, and access and load the file specified by filepath.Join in template.ParseFiles. And finally it is stored in the tmpl of the structure.

At the end of the method, write to http communication with .Evecute.

Now let's look at the main function.

func main() {
	http.Handle("/", &templateHandler{filename: "template1.html"})
	log.Fatal(http.ListenAndServe(":8080", nil))
}

I explained the inside of the main function last time. This time, specify the element with {filename: "filename"} in & templeHandler. For this file, create a "templates" folder in the folder where the go script is saved, and save the .html file in it.

Recommended Posts

Create a web server in Go language (net/http) (2)
Create a web service in Flask-SQLAlchemy + PostgreSQL
Create an executable file in a scripting language
Set up a UDP server in C language
Create a fake Minecraft server in Python with Quarry
Create a function in Python
Create a dictionary in Python
Create a (simple) REST server
Hello World in GO language
Create a simple textlint server
[Go language] Try to create a uselessly multi-threaded line counter
Try implementing Yubaba in Go language
Use optinal type-like in Go language
Create a CSV reader in Flask
Create a DI Container in Python
Create a binary file in Python
Post to slack in Go language
Start SQLite in a programming language
Create a Unix Domain Socket server
Create a Kubernetes Operator in Python
Write tests in GO language + gin
Create a random string in Python
Create a LINE Bot in Django
Do something object-oriented in GO language
Created a package to support AWS Lambda development in Go language
Created gomi, a trash can tool for rm in Go language
[Python / Django] Create a web API that responds in JSON format
Read the config file in Go language! Introducing a simple sample
Create a function to get the contents of the database in Go
Start the web server in the current directory
Display matplotlib diagrams in a web application
Create a simple GUI app in Python
Create a JSON object mapper in Python
[GO language] Let's read a YAML file
I made a kind of simple image processing tool in Go language.
Create a simple web app with flask
Create a Python-GUI app in Docker (PySimpleGUI)
Build a web server on your Chromebook
Create a web service with Docker + Flask
Web application development in Go language_Hands-on day 1
Create a high-level synthesis language assembler. Part 6
Put Docker in Windows Home and run a simple web server with Python
Go beginner tried to create a cloud native web application using Datastore / GAE
Create a Django project and application in a Python virtual environment and start the server
[Python] How to create a local web server environment with SimpleHTTPServer and CGIHTTPServer
Set up a simple HTTPS server in Python 3
Create a Vim + Python test environment in 1 minute
Create a GIF file using Pillow in Python
Java programmer touched Go language (Implement Java inheritance in Go language)
Book updated: Evolving into a "decent web server"
Create a standard normal distribution graph in Python
Create a virtual environment with conda in Python
Set up a test SMTP server in Python.
Create a web map using Python and GDAL
Steps to develop a web application in Python
Create a protein sequence mutation library in pandas
Create a custom search command in Splunk (Streaming Command)
Launch a web server with Python and Flask
I wrote the hexagonal architecture in go language
Set up a simple SMTP server in Python
Create a package containing global commands in Python