Location>code7788 >text

Reading notes for Building Distributed Applications with the Gin Framework: p77-p87

Popularity:435 ℃/2024-10-17 23:37:15

Learning Day 5 of Building Distributed Applications with the Gin Framework, p77-p87 Summary, 11 pages in total.

I. Technical summary

point of knowledge (math.)

(1)context

-premises software

p80, A container is like a separate OS, but not virtualized; it only contains the dependencies needed for that one application, which makes the container portable and deployable on-premises or on the cloud。

Premises means "the land and buildings owned by someone, especially by a company or organization". Simply put, on-premises software refers to services (software) that run locally.

wiki Good definition of the name,Here's a direct quote“On-premises software (abbreviated to on-prem, and often written as "on-premise") is installed and runs on computers on the premises of the person or organization using the software, rather than at a remote facility such as a server farm or cloud”。

rand command

openssl rand -base64 12 | docker secret create mongodb_password
-

rand command syntax:

openssl rand [-help] [-out file] [-base64] [-hex] [-engine id] [-rand files] [-writerand file] [-provider name] [-provider-path path] [-propquery propq] num[K|M|G|T]

12 corresponds to the num parameter. rand is described in detail in /3.4/man1/openssl-rand/. For a command, we need to know what parameters it has and the meaning of each parameter.

4. Check the version number corresponding to the docker latest tag

(1) Undownloaded mirrors

Open the page corresponding to the latest tag, for example:/layers/library/mongo/latest/images/sha256-e6e25844ac0e7bc174ab712bdd11bfca4128bf64d28f85d0c6835c979e4a5ff9, search for VERSION and then find the version number.

(2) Downloaded mirrors

Use the docker inspect command to view it.

# docker inspect d32 | grep -i version
        "DockerVersion": "",
                "GOSU_VERSION=1.17",
                "JSYAML_VERSION=3.13.1",
                "MONGO_VERSION=8.0.1",
                "": "24.04"

-go-driver example

The code in the book uses mongo-go-driver v1.4.5, which has now been updated to v2.0.0, which makes some of the code unusable, so it is recommended to use the latest version. The Go ecosystem's documentation is horribly written. Example:

client, _ := (().ApplyURI("mongodb://localhost:27017"))
ctx, cancel = ((), 2*)
defer cancel()

_ = (ctx, ())

Personally, I don't think the above code err should be ignored. Instead, it should be:

package main

import (
	"context"
	"/gin-gonic/gin"
	"/rs/xid"
	"/mongo-driver/v2/mongo"
	"/mongo-driver/v2/mongo/options"
	"/mongo-driver/v2/mongo/readpref"
	"log"
	"net/http"
	"strings"
	"time"
)

type Recipe struct {
	ID string `json:"id"`
	Name string `json:"name"`
	Tags []string `json:"tags"`
	Ingredients []string `json:"ingredients"`
	Instructions []string `json:"instructions"`
	PublishAt `json:"publishAt"`
}

var recipes []Recipe

func init() {
	// way (of life)1:Initialization using memory
	// recipes = make([]Recipe, 0)
	// file, err := ("")
	// if err != nil {
	// (err)
	// return
	// }
	// defer ()
	//
	// // deserialization:commander-in-chief (military)jsonchange over toslice
	// decoder := (file)
	// err = (&recipes)
	// if err != nil {
	// (err)
	// return
	// }

	// way (of life)2:utilization MongoDB Stored Data
	ctx, cancel := ((), 10*)
	defer cancel()
	// Create Connection,Here. err Target. URI incorrect
	client, err := (().ApplyURI("mongodb1://admin:admin@localhost:27017"))
	if err != nil {
		("MongoDB connect error: ", err)
	}

	// Determine if the connection is successful
	if err := (ctx, ()); err != nil {
		("MongoDB Ping error: ", err)
	}

	("Connected to MongoDB successfully.")

}

// swagger:route POST /recipes createRecipe
//
// # Create a new recipe
//
// Responses:
//
// 200: recipeResponse
//
// NewRecipeHandler additionalrecipe,是按照单个additional,So here the name here is in the singular
func NewRecipeHandler(c *) {
	var recipe Recipe
	if err := (&recipe); err != nil {
		(, {"error": ()})
		return
	}
	 = ().String()
	 = ()
	recipes = append(recipes, recipe)
	(, recipe)
}

// swagger:route GET /recipes listRecipes
// Returns list of recipes
// ---
// produces:
// - application/json
// responses:
// '200':
// description: Successful operation
// ListRecipesHandler differrecipes,Because it's a query for all,So the name is in the plural here
func ListRecipesHandler(c *) {
	(, recipes)
}

// UpdateRecipeHandler update recipe,Because it's a single,所以utilization的是单数。
// id through (a gap) path gain,其它参数through (a gap) body gain。
func UpdateRecipeHandler(c *) {
	id := ("id")

	// data decoding
	var recipe Recipe
	if err := (&recipe); err != nil {
		(, {"error": ()})
		return
	}
	// judgements id whether or not
	index := -1
	for i := 0; i < len(recipes); i++ {
		if recipes[i].ID == id {
			index = i
		}
	}

	// in the event that id non-existent
	if index == -1 {
		(, {"error": "recipe not found"})
		return
	}
	// in the event that id 存在则进行update
	recipes[index] = recipe
	(, recipe)
}

// DeleteRecipeHandler removing recipe: 1.removing之前judgementswhether or not,存在就removing,non-existent就提示non-existent。
func DeleteRecipeHandler(c *) {
	id := ("id")
	index := -1
	for i := 0; i < len(recipes); i++ {
		if recipes[i].ID == id {
			index = i
		}
	}

	if index == -1 {
		(, {"message": "recipe not found"})
		return
	}
	recipes = append(recipes[:index], recipes[index+1:]...)
	(, {
		"message": "recipe deleted",
	})
}

// SearchRecipesHandler consult (a document etc) recipes
func SearchRecipesHandler(c *) {
	tag := ("tag")
	listOfRecipes := make([]Recipe, 0)

	for i := 0; i < len(recipes); i++ {
		found := false
		for _, t := range recipes[i].Tags {
			if (t, tag) {
				found = true
			}
			if found {
				listOfRecipes = append(listOfRecipes, recipes[i])
			}
		}
	}
	(, listOfRecipes)
}
func main() {
	router := ()
	("/recipes", NewRecipeHandler)
	("/recipes", ListRecipesHandler)
	("/recipes/:id", UpdateRecipeHandler)
	("/recipes/:id", DeleteRecipeHandler)
	("/recipes/search", SearchRecipesHandler)
	err := ()
	if err != nil {
		return
	}
}

II. English summary

p79, I opted to go with Docker duce to its popularity and simplicity in runing ephermeral environment.

(1)ephemeral: ephemera + -al。

(2)ephemera: epi-("on") + hemera("day"), lasting one day , short-lived"。

III. Other

From the reading experience so far, the author defaults to the reader's full mastery of Golang and does not expand on the introduction in any way.

IV. References

1. Programming

(1) Mohamed Labouardy,《Building Distributed Applications in Gin》:/subject/35610349

2. English

(1) Etymology Dictionary:

(2) Cambridge Dictionary:

Welcome to search and follow: programmers (a_codists)