亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home Backend Development Golang Does go language not support aop?

Does go language not support aop?

Dec 27, 2022 pm 05:04 PM
golang go language aop Aspect Oriented Programming

Go language supports aop. AOP refers to aspect-oriented programming, which is a technology that achieves unified maintenance of program functions through pre-compilation and dynamic agents during runtime; AOP is an object-oriented approach, with main application scenarios: logging, performance statistics, security control , transaction processing, exception handling, etc.

Does go language not support aop?

The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.

What is aop?

In the software industry, AOP is the abbreviation of Aspect Oriented Programming, which means: Aspect-oriented programming, a technology that achieves unified maintenance of program functions through pre-compilation and dynamic agents during runtime . AOP is the continuation of OOP, a hot spot in software development, an important content in the Spring framework, and a derivative paradigm of functional programming. AOP can be used to isolate various parts of the business logic, thereby reducing the coupling between the various parts of the business logic, improving the reusability of the program, and improving the efficiency of development.

Aspect-oriented programming is just a method in object-oriented. Dynamically embedding other code during code execution is called aspect-oriented programming. Common usage scenarios:

  • Log

  • Things

  • Database Operation

Aspect-oriented programming is to encapsulate cross-business logic into aspects and use the functions of AOP to weave aspects into the main business logic. The so-called cross-business logic refers to general code that has nothing to do with the main business logic, such as security checks, things, logs, etc. If AOP is not used, code entanglement will occur, that is, cross-business logic is mixed with main business logic. In this way, the business logic will become confusing.

Main application scenarios: logging, performance statistics, security control, transaction processing, exception handling, etc.

Core Concept

  • JoinPoint: Connection point. It is a precise execution point in program execution, such as a method in a class.

  • PointCut: entry point. Specify which components and which methods use aspect components.

  • Advice: Notification, used to specify the location of specific effects, before or after the method, etc., divided into pre-notification, post-notification, exception notification, return notification, and surrounding notification .

  • Aspect: Aspect. Components that encapsulate common business logic, that is, the code content we want to insert.

The inherent design pattern is the proxy pattern.

Does the go language support aop?

go language supports aop.

Example of Go implementation of AOP:

// User 
type User struct {
	Name string
	Pass string
}

// Auth 驗(yàn)證
func (u *User) Auth() {
	// 實(shí)際業(yè)務(wù)邏輯
	fmt.Printf("register user:%s, use pass:%s\n", u.Name, u.Pass)
}


// UserAdvice 
type UserAdvice interface {
    // Before 前置通知
    Before(user *User) error
    
    // After 后置通知
	After(user *User)
}

// ValidatePasswordAdvice 用戶(hù)名驗(yàn)證
type ValidateNameAdvice struct {
}

// ValidatePasswordAdvice 密碼驗(yàn)證
type ValidatePasswordAdvice struct {
	MinLength int
	MaxLength int
}

func (ValidateNameAdvice) Before(user *User) error {
	fmt.Println("ValidateNameAdvice before")
	if user.Name == "admin" {
		return errors.New("admin can't be used")
	}

	return nil
}

func (ValidateNameAdvice) After(user *User) {
	fmt.Println("ValidateNameAdvice after")
	fmt.Printf("username:%s validate sucess\n", user.Name)
}

// Before 前置校驗(yàn)
func (advice ValidatePasswordAdvice) Before(user *User) error {
	fmt.Println("ValidatePasswordAdvice before")
	if user.Pass == "123456" {
		return errors.New("pass isn't strong")
	}

	if len(user.Pass) > advice.MaxLength {
		return fmt.Errorf("len of pass must less than:%d", advice.MaxLength)
	}

	if len(user.Pass) < advice.MinLength {
		return fmt.Errorf("len of pass must greater than:%d", advice.MinLength)
	}

	return nil
}

func (ValidatePasswordAdvice) After(user *User) {
	fmt.Println("ValidatePasswordAdvice after")
	fmt.Printf("password:%s validate sucess\n", user.Pass)
}

// UserAdviceGroup,通知管理組
type UserAdviceGroup struct {
	items []UserAdvice
}

// Add 注入可選通知
func (g *UserAdviceGroup) Add(advice UserAdvice) {
	g.items = append(g.items, advice)
}

func (g *UserAdviceGroup) Before(user *User) error {
	for _, item := range g.items {
		if err := item.Before(user); err != nil {
			return err
		}
	}

	return nil
}

// After
func (g *UserAdviceGroup) After(user *User) {
	for _, item := range g.items {
		item.After(user)
	}
}

// UserProxy 代理,也是切面
type UserProxy struct {
	user *User
}

// NewUser return UserProxy
func NewUser(name, pass string) UserProxy {
	return UserProxy{user:&User{Name:name, Pass:pass}}
}

// Auth 校驗(yàn),切入點(diǎn)
func (p UserProxy) Auth() {
	group := UserAdviceGroup{}
	group.Add(&ValidatePasswordAdvice{MaxLength:10, MinLength:6})
    group.Add(&ValidateNameAdvice{})
    
    // 前置通知
	if err := group.Before(p.user); err != nil {
		panic(err)
	}

    // 實(shí)際邏輯
	p.user.Auth()

    // 后置通知
	group.After(p.user)

}

Use AOP mode for decoupling and separation of main business and secondary business. In fact, that's it.

【Related recommendations: Go video tutorial, Programming teaching

The above is the detailed content of Does go language not support aop?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
Use PhpStorm to build a Go language development environment Use PhpStorm to build a Go language development environment May 20, 2025 pm 07:27 PM

PhpStorm was chosen for Go development because I was familiar with the interface and rich plug-in ecosystem, but GoLand was more suitable for focusing on Go development. Steps to build an environment: 1. Download and install PhpStorm. 2. Install GoSDK and set environment variables. 3. Install the Go plug-in in PhpStorm and configure the GoSDK. 4. Create and run the Go project.

Strategies for Integrating Golang Services with Existing Python Infrastructure Strategies for Integrating Golang Services with Existing Python Infrastructure Jul 02, 2025 pm 04:39 PM

TointegrateGolangserviceswithexistingPythoninfrastructure,useRESTAPIsorgRPCforinter-servicecommunication,allowingGoandPythonappstointeractseamlesslythroughstandardizedprotocols.1.UseRESTAPIs(viaframeworkslikeGininGoandFlaskinPython)orgRPC(withProtoco

Best practices and tips for reducing Docker image volume Best practices and tips for reducing Docker image volume May 19, 2025 pm 08:42 PM

Methods to reduce the volume of Docker image include: 1. Use .dockerignore files to exclude unnecessary files; 2. Select a streamlined basic image, such as the alpine version; 3. Optimize Dockerfile, merge RUN commands and use the --no-cache option; 4. Use multi-stage construction to copy only the files that are needed in the end; 5. Manage dependent versions and regularly clean up dependencies that are no longer used. These methods not only reduce the image volume, but also improve the application startup speed and operation efficiency.

Go 'encoding/binary' Package: Read, Write, Pack & Unpack Go 'encoding/binary' Package: Read, Write, Pack & Unpack May 21, 2025 am 12:10 AM

Go'sencoding/binarypackageiscrucialforhandlingbinarydata,offeringstructuredreadingandwritingcapabilitiesessentialforinteroperability.Itsupportsvariousdatatypesandendianness,makingitversatileforapplicationslikenetworkprotocolsandfileformats.Useittoeff

Golang's security settings on Debian Golang's security settings on Debian May 16, 2025 pm 01:15 PM

When setting up a Golang environment on Debian, it is crucial to ensure system security. Here are some key security setup steps and suggestions to help you build a secure Golang development environment: Security setup steps System update: Make sure your system is up to date before installing Golang. Update the system package list and installed packages with the following command: sudoaptupdatesudoaptupgrade-y Firewall Configuration: Install and configure a firewall (such as iptables) to limit access to the system. Only necessary ports (such as HTTP, HTTPS, and SSH) are allowed. sudoaptininstalliptablessud

How to use the 'bytes' package to manipulate byte slices in Go (step by step) How to use the 'bytes' package to manipulate byte slices in Go (step by step) May 12, 2025 am 12:01 AM

ThebytespackageinGoishighlyeffectiveforbyteslicemanipulation,offeringfunctionsforsearching,splitting,joining,andbuffering.1)Usebytes.Containstosearchforbytesequences.2)bytes.Splithelpsbreakdownbyteslicesusingdelimiters.3)bytes.Joinreconstructsbytesli

Understanding the Performance Differences Between Golang and Python for Web APIs Understanding the Performance Differences Between Golang and Python for Web APIs Jul 03, 2025 am 02:40 AM

Golangofferssuperiorperformance,nativeconcurrencyviagoroutines,andefficientresourceusage,makingitidealforhigh-traffic,low-latencyAPIs;2.Python,whileslowerduetointerpretationandtheGIL,provideseasierdevelopment,arichecosystem,andisbettersuitedforI/O-bo

Mastering Binary Data Handling with Go's 'encoding/binary' Package: A Comprehensive Guide Mastering Binary Data Handling with Go's 'encoding/binary' Package: A Comprehensive Guide May 13, 2025 am 12:07 AM

Theencoding/binarypackageinGoisessentialbecauseitprovidesastandardizedwaytoreadandwritebinarydata,ensuringcross-platformcompatibilityandhandlingdifferentendianness.ItoffersfunctionslikeRead,Write,ReadUvarint,andWriteUvarintforprecisecontroloverbinary

See all articles