<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>Technical Blog on seth-shi</title><link>https://www.shiguopeng.cn/en/posts/</link><description>Recent content in Technical Blog on seth-shi</description><generator>Hugo -- gohugo.io</generator><language>zh-CN</language><lastBuildDate>Wed, 08 Oct 2025 13:36:17 +0800</lastBuildDate><atom:link href="https://www.shiguopeng.cn/en/posts/index.xml" rel="self" type="application/rss+xml"/><item><title>A Zero-Dependency, Multi-Language, Multi-Currency, Multi-Tenant Apple Refund Management Assistant</title><link>https://www.shiguopeng.cn/en/posts/2025100813-en/</link><pubDate>Wed, 08 Oct 2025 13:36:17 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2025100813-en/</guid><description>Open Source Github: https://github.com/seth-shi/apple-refund-assistant Overview This service is built on Laravel / Filament multi-tenant architecture, effectively helping developers prevent fraudulent refunds by instantly processing Apple&amp;rsquo;s CONSUMPTION_REQUEST notifications and asynchronously returning consumption data.
Multi-tenant Support Multi-language Support (中文 / English / Español / हिन्दी / العربية / Português / Русский / 日本語 / Français) Multi-currency Support Zero Dependency File+SQLite or upgrade to Redis+MySQL 100% Test Coverage Self-hosted App Keys Private keys are only stored in your database apps table (symmetric encryption, key generated by your application) 12 Consumption Fields - Calculate all required Apple fields Notification Message Forwarding Apple servers send to current service, current service forwards to your production server Online Demo 🌐 Demo URL: https://apple-refund-assistant.</description></item><item><title>Make Your Hugo Blog Multilingual</title><link>https://www.shiguopeng.cn/en/posts/2025042410/</link><pubDate>Thu, 24 Apr 2025 10:42:53 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2025042410/</guid><description>Preface First of all, Hugo cannot achieve automatic redirection because it is essentially a static site generator. https://discourse.gohugo.io/t/auto-detect-browser-preferred-language/8391 Implementation The theme I&amp;rsquo;m using is https://github.com/CaiJimmy/hugo-theme-stack. Others can be modified as needed. Add language configuration in config.toml: languages: zh-cn: languageName: Chinese weight: 1 en: languageName: English title: &amp;#34;seth-shi&amp;#34; weight: 2 add a switch language button layouts/partials/sidebar/left.html &amp;lt;li id=&amp;#34;lang-switcher&amp;#34;&amp;gt; {{ range .Site.Languages }} &amp;lt;a data-url=&amp;#34;{{ .Lang | relURL }}&amp;#34; href=&amp;#34;javascript:void(0);&amp;#34; class=&amp;#34;lang-item {{ if eq .</description></item><item><title>Calling C++ Dynamic Libraries in Python</title><link>https://www.shiguopeng.cn/en/posts/2025032821/</link><pubDate>Fri, 28 Mar 2025 21:31:03 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2025032821/</guid><description>When working on a Python project recently, I needed to call C++ dynamic library files. Both Python&amp;rsquo;s built-in ctypes library and the pybind11 library can interface with dynamic libraries. ctypes Use ctypes for simple data types - it&amp;rsquo;s preinstalled with Python and straightforward to use However, when dealing with C++ complex types like vector, it throws Segmentation fault (core dumped) errors because ctypes lacks native support for vector type mapping Reference: https://stackoverflow.</description></item><item><title>In-Depth Understanding of HTTP Range and Video Streaming Mechanisms</title><link>https://www.shiguopeng.cn/en/posts/2025031416/</link><pubDate>Fri, 14 Mar 2025 16:05:31 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2025031416/</guid><description>Deep Dive into MP4 File Structure When metadata is at the beginning, [mdat] and [moov] swap positions +---------------------------------------------------------------+ | MP4 File Structure | | | | +--------+ +--------+ +--------+ | | | [ftyp] | ------&amp;gt; | [mdat] | ------&amp;gt; | [moov] | | | +--------+ +--------+ +--------+ | | File Type Box Media Data Metadata Container | | | | | +---------------------+ | | | | | +--------------------------------------------------+ | | | [moov] | | | | +-----------------------------+ | | | | | [mvhd] | | | | | +-----------------------------+ | | | | Movie Header Box | | | | | | | | +-----------------------------+ | | | | | [trak] | | | | | +-----------------------------+ | | | | Track Container | | | | / \ | | | | / \ | | | | +-------------+ +-------------+ | | | | | [tkhd] | | [mdia] | | | | | +-------------+ +-------------+ | | | | Track Header Media Box | | | | | | | | | | | | | | +------------------+ | | | | | [minf] | | | | | +------------------+ | | | | Media Info Box | | | | / \ | | | | / \ | | | | +-------------+ +-------------+ | | | | | [vmhd/smhd] | | [stbl] | | | | | +-------------+ +-------------+ | | | | Video/Audio Box Sample Table | | | | | | | | | +------------------+ | | | | | | | | | | | +-------------+ | | | | | | | [stsd] | | | | | | | +-------------+ | | | | | | Sample Desc.</description></item><item><title>Troubleshooting High Memory Usage in PHP Queue Service</title><link>https://www.shiguopeng.cn/en/posts/2025010714/</link><pubDate>Tue, 07 Jan 2025 14:19:05 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2025010714/</guid><description>The operations team reported recurring OOM (Out-Of-Memory) restarts in a container pod. Monitoring data showed periodic memory spikes: 1.png The service in question handles video composition via queue jobs. It uses shell_exec to invoke commands like ffmpeg and spleeter for audio processing and quality adjustments.
Since external command execution isn&amp;rsquo;t trackable through PHP&amp;rsquo;s memory monitoring, we used atop for detailed logging.
Service Setup ## Installation apt update &amp;amp;&amp;amp; apt install -y atop ## Modify the configuration file cat /etc/default/atop LOGOPTS=&amp;#34;&amp;#34; LOGINTERVAL=1 # Set to 1s for granular monitoring LOGGENERATIONS=28 # Retain logs for 28 days LOGPATH=/var/log/atop ## Start service systemctl start atop Diagnosis Process Alibaba Cloud monitoring showed a memory spike at 16:20:30: img.</description></item><item><title>Why Can otel.GetTracerProvider() Followed by otel.SetTracerProvider() Still Report Successfully in Go Tracing?</title><link>https://www.shiguopeng.cn/en/posts/2024092311/</link><pubDate>Mon, 23 Sep 2024 11:14:49 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2024092311/</guid><description>Recently, when integrating internal tracing in go-zero using some third-party packages, part of the code is as follows: package main import ( &amp;#34;fmt&amp;#34; &amp;#34;github.com/zeromicro/go-zero/zrpc&amp;#34; ) func main() { // 1. Get service configuration svcCtx := svc.NewServiceContext() // 2. Initialize server (this actually calls otel.SetTracerProvider()) // server.NewServer() =&amp;gt; // service.SetUp =&amp;gt; // trace.StartAgent =&amp;gt; // trace.startAgent() =&amp;gt; // otel.SetTracerProvider() s := zrpc.MustNewServer() defer s.Stop() fmt.Printf(&amp;#34;Starting rpc server at %s...\n&amp;#34;, svcCtx.Config.ListenOn) s.Start() } package svc import ( &amp;#34;time&amp;#34; &amp;#34;github.</description></item><item><title>Notes on Writing Tests with go-zero + gorm</title><link>https://www.shiguopeng.cn/en/posts/2024082617/</link><pubDate>Mon, 26 Aug 2024 17:33:52 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2024082617/</guid><description>Getting Started Testing Methods &amp;amp; Approaches export_test.go: Used for test data definitions without affecting production code Setup/Teardown patterns: func setUp(testName string) func() { fmt.Printf(&amp;#34;\tsetUp fixture for %s\n&amp;#34;, testName) return func() { fmt.Printf(&amp;#34;\ttearDown fixture for %s\n&amp;#34;, testName) } } func TestFunc1(t *testing.T) { defer setUp(t.Name())() fmt.Printf(&amp;#34;\tExecute test: %s\n&amp;#34;, t.Name()) } func TestMain(m *testing.M) { defer pkgSetUp(&amp;#34;package demo_test&amp;#34;)() m.Run() } Unit Testing
Core business logic in go-zero services (e.g., logic layer) Mock dependencies using: sql-mock for databases redismock for Redis testify-mock for other interfaces Alternative mocking solutions: monkey Integration Testing</description></item><item><title>Integrating SonarQube into Golang Projects for Code Quality Analysis</title><link>https://www.shiguopeng.cn/en/posts/2024080117/</link><pubDate>Thu, 01 Aug 2024 17:40:53 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2024080117/</guid><description>Installation and Configuration Installation Binary installation: https://www.sonarsource.com/products/sonarqube/downloads/ Recommended Docker deployment (note volume mounting): https://docs.sonarsource.com/sonarqube/latest/setup-and-upgrade/install-the-server/installing-sonarqube-from-docker/ Install Chinese Pack plugin (optional) 1.png Configure Gitlab Login Documentation: https://docs.sonarsource.com/sonarqube/10.1/instance-administration/authentication/gitlab/
Create application at https://&amp;lt;Your Gitlab URL&amp;gt;/-/profile/applications (read_user permission) Callback URL must be &amp;lt;Your SonarQube URL&amp;gt;/oauth2/callback/gitlab Gitlab login button should appear after configuration
Server base URL must be configured for successful redirection 2.png 3.png 4.png Configure Gitlab project import Create Token at https://&amp;lt;Your Gitlab URL&amp;gt;/-/profile/personal_access_tokens Gitlab API endpoint: https://&amp;lt;Your Gitlab URL&amp;gt;/api/v4 Gitlab option will appear in project creation after successful configuration 5.</description></item><item><title>Upgrading from Laravel5 to Laravel10: A Journey with Octane Containerization and Horizon Integration</title><link>https://www.shiguopeng.cn/en/posts/2024042811/</link><pubDate>Sun, 28 Apr 2024 11:02:51 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2024042811/</guid><description>While working on upgrading PHP versions, I took the opportunity to upgrade https://github.com/seth-shi/monday-shop from Laravel5 to Laravel10. Existing Solutions Paid option: https://laravelshift.com/ Open-source helper: https://laravel-upgrade-helper.github.io/ Upgrade Process Project Preparation Assume project path: /var/www/monday-shop Create a new Laravel10 project within the same directory: composer create-project laravel/laravel=10.* laravel10 New project path: /var/www/monday-shop/laravel10 Dependency Management Update dependencies: Merge require and require-dev sections from /var/www/monday-shop/laravel10/composer.json Delete old /var/www/monday-shop/composer.lock Resolve dependency conflicts: # Example conflict resolution composer install # Handle version conflicts iteratively Verify unused dependencies with composer depends xxx/xxxx File Migration Copy core files from new Laravel10 project: # Maintain directory structure while preserving custom modifications ├─app ├─bootstrap ├─config ├─database ├─public ├─resources ├─routes ├─storage ├─tests Process files folder-by-folder, comparing with custom implementations Error Resolution Start development server: php artisan serve Monitor storage/logs for errors Install missing helpers: composer require laravel/helpers Containerization with Octane Replace legacy laravel-s with official Octane: composer require laravel/octane Implement containerization using laravel-octane-dockerfile Key Configuration Files .</description></item><item><title>PHP-roadrunner Stress Testing and Configuration Tuning</title><link>https://www.shiguopeng.cn/en/posts/2024042417/</link><pubDate>Wed, 24 Apr 2024 17:50:27 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2024042417/</guid><description>Pod Configuration CPU Memory 0.5 512M Testing Tool Alibaba Cloud PTS Concurrency Duration Source Test Endpoint 100 2 min Public /api/welcome Note: 100 concurrency was determined after initial testing as the maximum load the pod could handle without errors (200 concurrency caused significant RT increases).
Service Startup RoadRunner architecture:
RoadRunner Architecture Laravel Octane natively supports RoadRunner. Start the HTTP service with:
php artisan octane:start --server=roadrunner --host=0.0.0.0 --port=8080 --rpc-port=6001 --workers=1 --log-level=warn --max-requests=50000 --rr-config=/var/www/.</description></item><item><title>Discontinuous Time Segments in Tracing with opentelemetry-auto-laravel in PHP</title><link>https://www.shiguopeng.cn/en/posts/2024032815/</link><pubDate>Thu, 28 Mar 2024 15:15:29 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2024032815/</guid><description>The Main Course Time segment issue Found discontinuous time segments when implementing opentelemetry tracing in PHP projects Integration Configuration (Click to expand details) Integration Install extensions (Automatic reporting requires PHP8) https://opentelemetry.io/docs/languages/php/automatic/ opentelemetry extension Container installation: install-php-extensions opentelemetry Windows DLL: https://phpext.phptools.online/extension/php/opentelemetry-261 Composer package: composer install open-telemetry/opentelemetry-auto-laravel Configuration ### Debugging reporting logs OTEL_LOG_LEVEL=debug OTEL_PHP_LOG_DESTINATION=stdout TEL_PHP_AUTOLOAD_ENABLED=true TEL_SERVICE_NAME=test TEL_TRACES_EXPORTER=otlp TEL_METRICS_EXPORTER=none TEL_LOGS_EXPORTER=none TEL_EXPORTER_OTLP_PROTOCOL=grpc TEL_EXPORTER_OTLP_ENDPOINT=http:// TEL_EXPORTER_OTLP_HEADERS=Authentication=xxx TEL_EXPORTER_OTLP_TIMEOUT=1000 TEL_EXPORTER_OTLP_TRACES_TIMEOUT=1000 Implementation open-telemetry/opentelemetry-auto-laravel auto-loads via _register.php in composer.json Default instrumentation: request, cache, log, http client Uses BatchSpanProcessor by default from SDK configuration Sample Code Custom tracer class &amp;lt;?</description></item><item><title>Handling Apple Payment Server Callbacks Like WeChat Pay</title><link>https://www.shiguopeng.cn/en/posts/2024031416/</link><pubDate>Thu, 14 Mar 2024 16:01:34 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2024031416/</guid><description>Client-side implementation should use StoreKit2. For server-side notifications, refer to Apple&amp;rsquo;s official documentation.
Database Design (Simplified) # Order Table mysql&amp;gt; desc orders; +------------------+---------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------------+---------------------+------+-----+---------+----------------+ | id | bigint(20) unsigned | NO | PRI | NULL | auto_increment | | no | varchar(255) | NO | UNI | NULL | | | trade_no | varchar(255) | YES | | NULL | | | status | tinyint(4) | NO | | NULL | | | origin_no | varchar(255) | YES | | NULL | | +------------------+---------------------+------+-----+---------+----------------+ # User Subscription Contracts Table mysql&amp;gt; desc member_contracts; +-----------------+---------------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-----------------+---------------------+------+-----+---------+-------+ | user_id | bigint(20) unsigned | NO | PRI | NULL | | | status | tinyint(4) | NO | | NULL | | | contract_id | varchar(255) | NO | MUL | NULL | | +-----------------+---------------------+------+-----+---------+-------+ Server-Side Processing Logic Resubscription after expiration changes both appAccountToken and originalTransactionId (after subscription cancellation and expiration) Resubscription during active period retains the same appAccountToken and originalTransactionId Client-Side Order Creation ## Client requests order creation API to generate order number `$uuid` ## Return this value to client for `appAccountToken` usage INSERT INTO orders(no) VALUES(&amp;#39;$uuid&amp;#39;); Subscription Event Callback Handling Apple Server notificationV2 callback &amp;amp;&amp;amp; client-side verification (a JWS string) ## Parse server callback, verify notificationType=SUBSCRIBED and subtype in (INITIAL_BUY, RESUBSCRIBE, AUTO_RENEW_ENABLED) ## Key fields: appAccountToken, transactionId, originalTransactionId, expiresDate ## 1.</description></item><item><title>Building an Ethereum Vanity Address Generator with Distributed Computing Support</title><link>https://www.shiguopeng.cn/en/posts/2024030713/</link><pubDate>Thu, 07 Mar 2024 13:01:59 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2024030713/</guid><description>GitHub Repository: https://github.com/seth-shi/ethereum-wallet-generator-worker Full usage tutorial available in project README. Download pre-built binaries for all platforms from releases For Android devices, use Termux to run in background Demo Screenshot Current Progress Estimated 1 week to generate desired vanity address with 0x0000 prefix and 9999 suffix - now running Successfully Generated Address Ethereum Address: 0x0000f31fE398080ef162841Cae9111735C919999 Success Screenshot 1 Success Screenshot 2 Usage Guide Ethereum Vanity Address Generator GitHub: https://github.com/seth-shi/ethereum-wallet-generator-worker Important Notes Generated mnemonics are encrypted in wallet.</description></item><item><title>Automatically Run Top on Secondary Screen at Windows Startup to Monitor Process Usage</title><link>https://www.shiguopeng.cn/en/posts/2024022015/</link><pubDate>Tue, 20 Feb 2024 15:23:59 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2024022015/</guid><description>Winget Installation (Choose one method. Using winget facilitates subsequent installations) Preinstalled in Windows 11 Microsoft Store GitHub Release Verify installation: C:\Users\seth-shi&amp;gt;winget --version v1.6.3482 Windows Terminal Install: winget install -e --id Microsoft.WindowsTerminal Configure fullscreen startup as shown: 1.png NTop Install: winget install -e --id gsass1.NTop Launch: ntop -s &amp;quot;mem&amp;quot; (See documentation at https://github.com/gsass1/NTop for more parameters) 2.png Task Scheduler Press Win+R, type taskschd.msc to open Task Scheduler Configuration Create Basic Task Trigger: At system startup Action: Start a program Launch parameters: wt --pos=1000 ntop -s &amp;quot;mem&amp;quot; wt launches Windows Terminal --pos positions window on secondary screen (omit for single display setups) 3.</description></item><item><title>Using gorm gen in go-zero</title><link>https://www.shiguopeng.cn/en/posts/2023102415/</link><pubDate>Tue, 24 Oct 2023 15:49:25 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2023102415/</guid><description>Since the built-in sqlx in go-zero is too cumbersome to use, and it&amp;rsquo;s unbearable to write so many magic strings, this article introduces how to integrate gorm into go-zero.
Code Implementation // cmd/gen.go package main import ( &amp;#34;fmt&amp;#34; &amp;#34;path&amp;#34; &amp;#34;gorm.io/driver/mysql&amp;#34; &amp;#34;gorm.io/gen&amp;#34; &amp;#34;gorm.io/gen/field&amp;#34; &amp;#34;gorm.io/gorm&amp;#34; ) var ( // Modify these when generating for other services mysqlDsn = &amp;#34;xxx:xxx@tcp(127.0.0.1:3306)/xxx?charset=utf8mb4&amp;amp;loc=Local&amp;amp;parseTime=true&amp;#34; outPath = path.Join(&amp;#34;..&amp;#34;, &amp;#34;app&amp;#34;, &amp;#34;account&amp;#34;, &amp;#34;model&amp;#34;, &amp;#34;do&amp;#34;) modelPath = &amp;#34;entity&amp;#34; ) func main() { db, err := gorm.</description></item><item><title>Using gRPC Client for System Login in PHP Backend dcat-admin</title><link>https://www.shiguopeng.cn/en/posts/2023102010/</link><pubDate>Fri, 20 Oct 2023 10:38:05 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2023102010/</guid><description>Introduction The company has implemented a unified account center service using go-zero Some project backends built with dcat-admin need to authenticate users through this account center, documenting the implementation process Environment Setup Protobuf binary files from https://github.com/protocolbuffers/protobuf/releases Follow official documentation for installation: https://cloud.google.com/php/grpc?hl=zh-cn#windows For Windows: Download corresponding PHP version DLL from https://pecl.php.net/package/grpc Install packages: composer require &amp;#34;grpc/grpc:^1.38&amp;#34; composer require &amp;#34;google/protobuf:^3.17&amp;#34; For Docker (using mlocati/docker-php-extension-installer): RUN install-php-extensions grpc Generate PHP gRPC code requires grpc_php_plugin: Official guide: https://github.</description></item><item><title>Why Are 0.5-Core Pods on k8s So Busy?</title><link>https://www.shiguopeng.cn/en/posts/2023091320/</link><pubDate>Wed, 13 Sep 2023 20:05:42 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2023091320/</guid><description>Context Our CTO mentioned during a code review that our services run on 0.5-core Kubernetes pods and advised adjusting runtime parameters. Here&amp;rsquo;s what happened next:
Observation: Our Go services run on pods with 0.5 CPU cores but reported GOMAXPROCS=8 (matching the host machine&amp;rsquo;s 8-core configuration). Problem: This mismatch caused excessive CPU utilization due to thread contention. Solution: Using Uber&amp;rsquo;s automaxprocs to align GOMAXPROCS with the pod&amp;rsquo;s actual CPU limit resolved the issue.</description></item><item><title>Solution for Low Version Redis bitcount Offset Parameter Not Being Bits</title><link>https://www.shiguopeng.cn/en/posts/2023091221/</link><pubDate>Tue, 12 Sep 2023 21:22:58 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2023091221/</guid><description>Recently, we needed to implement a &amp;ldquo;check-in for N days to receive gifts&amp;rdquo; feature in a project. This naturally led us to consider using Redis&amp;rsquo; bitmap for implementation. Check-in can be done with setbit {key} {offset} 1 Cumulative check-in days can be retrieved using bitcount {key} {start} {end} index.md
Initially, we implemented it like this: # Base date example: 2023-09-12, offset 0 for this day setbit users:id 0 1 # Binary: 10000000 # Next day, 2023-09-13, offset 1 setbit users:id 1 1 # Binary: 11000000 # Retrieving check-in days from 2023-09-12 to 2023-09-20: bitcount users:id 0 8 # Output: 2.</description></item><item><title>Deploying Monitoring, Log Collection, and Alibaba Cloud ARMS with go-zero</title><link>https://www.shiguopeng.cn/en/posts/2023083117/</link><pubDate>Thu, 31 Aug 2023 17:50:44 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2023083117/</guid><description>Official steps from the documentation: https://go-zero.dev/docs/tutorials/monitor/index
Health Checks Name: user-api Host: 0.0.0.0 Port: 8002 DevServer: Enabled: true Port: 6470 HealthPath: &amp;#34;/healthz&amp;#34; Default health check port: 6470, default path: /healthz
You can use Alibaba Cloud&amp;rsquo;s Site Monitoring or similar services to periodically request this endpoint and ensure service availability.
Log Collection Logs can be written to stdout and aggregated using services like Alibaba Cloud SLS. Distributed Tracing Integration with Alibaba Cloud ARMS: https://arms.</description></item><item><title>Personal Single Server Microservices Practice</title><link>https://www.shiguopeng.cn/en/posts/2023082711/</link><pubDate>Sun, 27 Aug 2023 11:26:42 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2023082711/</guid><description>Preface Although I started working with microservices last year and deployed them on my personal server, they were all using direct connection mode. Today I took the opportunity to upgrade the go-zero codebase and revamp the architecture. Framework I continued using go-zero (https://github.com/zeromicro/go-zero) which was originally adopted last year, just updating to the latest version.
The code structure features a double-layer service under the root app directory, with shared code in pkg (e.</description></item><item><title>Building APIs Quickly with go-zero and gRPC Gateway</title><link>https://www.shiguopeng.cn/en/posts/2023081618/</link><pubDate>Wed, 16 Aug 2023 18:51:21 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2023081618/</guid><description>Official documentation provides a basic introduction. Here we&amp;rsquo;ll cover more advanced implementation details. Advanced Configuration Customizing request paths and methods hello.protobuf file syntax = &amp;#34;proto3&amp;#34;; package hello; option go_package = &amp;#34;./hello&amp;#34;; // Add import import &amp;#34;google/api/annotations.proto&amp;#34;; message Request { } message Response { string msg = 1; } service Hello { rpc Ping(Request) returns(Response) { // Add HTTP option option (google.api.http) = { post: &amp;#34;/api/v1/hello&amp;#34; body: &amp;#34;*&amp;#34; }; } } Update dependencies # Manually download annotations.</description></item><item><title>Force Returning Empty Data When MySQL Unexpectedly Crashes in Laravel</title><link>https://www.shiguopeng.cn/en/posts/2023062514/</link><pubDate>Sun, 25 Jun 2023 14:14:01 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2023062514/</guid><description>Background We previously encountered an issue where the service completely crashed when MySQL went down, with Redis failing to handle any requests. The normal business query logic is: Get data from Redis first, return if available If Redis has no data, query MySQL Write the retrieved data to Redis Return data Problem Analysis Redis itself wasn&amp;rsquo;t the issue - the problem occurred at step 2 When querying MySQL with the database service down, requests get blocked Blocking timeout leads to exceptions, preventing step 3 from executing Subsequent requests continue trying to connect to MySQL, creating infinite blocking that overloads the application servers Solution Our solution (may not fit all scenarios): Force caching empty data in Redis when MySQL crashes, allowing partial empty responses instead of service failure Implementation Approach Set appropriate MySQL connection timeout mysqlnd.</description></item><item><title>Implementation of OSS Browser Refresh and Resumable Upload Feature</title><link>https://www.shiguopeng.cn/en/posts/2023042711/</link><pubDate>Thu, 27 Apr 2023 11:09:55 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2023042711/</guid><description>Documentation: https://help.aliyun.com/document_detail/383953.html?spm=a2c4g.383947.0.0.47607d9dnkBjdG
Code Implementation &amp;lt;!DOCTYPE html&amp;gt; &amp;lt;html lang=&amp;#34;en&amp;#34;&amp;gt; &amp;lt;head&amp;gt; &amp;lt;meta charset=&amp;#34;UTF-8&amp;#34;/&amp;gt; &amp;lt;title&amp;gt;Document&amp;lt;/title&amp;gt; &amp;lt;/head&amp;gt; &amp;lt;body&amp;gt; &amp;lt;input type=&amp;#34;file&amp;#34; id=&amp;#34;file&amp;#34;&amp;gt; &amp;lt;span id=&amp;#34;process&amp;#34;&amp;gt;&amp;lt;/span&amp;gt; &amp;lt;button id=&amp;#34;submit&amp;#34;&amp;gt;Resume Upload&amp;lt;/button&amp;gt; &amp;lt;!-- Import SDK --&amp;gt; &amp;lt;script type=&amp;#34;text/javascript&amp;#34; src=&amp;#34;https://gosspublic.alicdn.com/aliyun-oss-sdk-6.16.0.min.js&amp;#34; &amp;gt;&amp;lt;/script&amp;gt; &amp;lt;script type=&amp;#34;text/javascript&amp;#34;&amp;gt; // Use multiple clients for multi-file uploads const client = new OSS({ // Replace yourRegion with actual region code region: &amp;#39;yourRegion&amp;#39;, // Get from STS service accessKeyId: &amp;#39;yourAccessKeyId&amp;#39;, accessKeySecret: &amp;#39;yourAccessKeySecret&amp;#39;, stsToken: &amp;#39;yourSecurityToken&amp;#39;, bucket: &amp;#34;examplebucket&amp;#34;, }); // Define checkpoint for resume let abortCheckpoint; // Get DOM elements let uploadFile; const process = document.</description></item><item><title>Upgrading from Flutter 2 to Flutter 3</title><link>https://www.shiguopeng.cn/en/posts/2023022521/</link><pubDate>Sat, 25 Feb 2023 21:55:31 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2023022521/</guid><description>Introduction Spent a day upgrading the architecture of Youmengji from Flutter 2 to Flutter 3. Here&amp;rsquo;s a summary of the pitfalls encountered.
Upgrading Flutter Version Check current version:
flutter --version Upgrade Flutter (requires VPN access):
flutter upgrade Verify version (should start with 3.x):
flutter --version If you&amp;rsquo;re lucky enough to run the app directly after this, you can stop reading here.
compileSdkVersion Error Modify compileSdkVersion to 33 in android/app/build.gradle Update distributionUrl in android/gradle/wrapper/gradle-wrapper.</description></item><item><title>Accessing Internal Network MySQL Database Locally via MobaXterm Xshell Tunneling</title><link>https://www.shiguopeng.cn/en/posts/2023020814/</link><pubDate>Wed, 08 Feb 2023 14:50:58 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2023020814/</guid><description>Context The test environment database resides in an internal network, while my computer can only connect via a jump server. To enable local code access, I tested MobaXterm for SSH tunneling.
Installation Download the free version from the official site: https://mobaxterm.mobatek.net/download.html 1.png Choose between the portable version (no installation) or installer. I selected the installer for straightforward setup. 2.png Configuration Open MobaXterm, navigate to Tunneling &amp;gt; New SSH tunnel 3.png Configure three key sections: ① Internal database server IP/port ② Jump server SSH credentials (IP, user, port) ③ Local port (choose an unused port) 4.</description></item><item><title>Xiaoai Assistant + Remote PC Power Control</title><link>https://www.shiguopeng.cn/en/posts/2023020720/</link><pubDate>Tue, 07 Feb 2023 20:19:01 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2023020720/</guid><description>My desktop PC is under the desk with a keyboard drawer, requiring me to bend down for power operations - quite inconvenient Purchased a PCI-E power control card (Taobao price: ¥35). Confirm your motherboard has compatible PCI-E slot (shown below) If unsure about motherboard compatibility, send your motherboard photo to customer service for verification
1.jpg Getting Started The power control card as received:
2.jpg Motherboard header diagram (key point: locate the POWER SW pins in bottom-right corner)</description></item><item><title>Advertising Attribution - A Comprehensive Guide to Attribution Architecture Implementation</title><link>https://www.shiguopeng.cn/en/posts/2023011214/</link><pubDate>Thu, 12 Jan 2023 14:58:55 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2023011214/</guid><description>Explanation Many concepts in this article reference insights from Sensors Data documentation. Attribution Methods Self-Attribution
Tracked by ad platforms. Some platforms receive app-open callbacks from users and perform attribution internally. Others like Huawei store attribution data locally during app installation, retrievable during first launch. Impression Attribution
Rarely used due to massive data volumes. Click Attribution (Most Common)
Attributes conversions to the last ad click before conversion. Attribution Models Last-Touch Model (Most Common)</description></item><item><title>Continuous Monthly Subscription - Periodic Deduction - Auto-Renewal Business Process Summary</title><link>https://www.shiguopeng.cn/en/posts/2022122914/</link><pubDate>Thu, 29 Dec 2022 14:45:32 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2022122914/</guid><description>Overview The terms &amp;ldquo;Continuous Monthly Subscription&amp;rdquo;, &amp;ldquo;Periodic Deduction&amp;rdquo;, and &amp;ldquo;Auto-Renewal&amp;rdquo; refer to the same core functionality:
Periodic Deduction - Official Alipay terminology Continuous Monthly Subscription - Common implementation pattern (also supports daily/quarterly) Auto-Renewal - User-facing behavior of automatic payment Deduction Scenarios Two implementation models:
Sign-then-Deduct
Redirect to agreement signing page User signs agreement Alipay async callback + immediate deduction Pay-then-Sign
Redirect to payment page (user can disable auto-renewal) User completes payment Receive two async notifications: payment &amp;amp; agreement Recommendation: Prefer Sign-then-Deduct to prevent users from disabling renewal during payment.</description></item><item><title>Using Protobuf Protocol Data in HTTP Requests</title><link>https://www.shiguopeng.cn/en/posts/2022101211/</link><pubDate>Wed, 12 Oct 2022 11:00:46 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2022101211/</guid><description>Recently I&amp;rsquo;ve been busy integrating third-party advertising platforms. During this process, I noticed that some API documentation was simply provided as Word documents with hundreds of parameters listed in tables, requiring manual parameter construction - a truly tedious process.
However, several providers stood out by offering .proto files, allowing automatic generation of Request and Response structures through protobuf - a developer-friendly approach worth applauding!
Key Takeaways When integrating APIs, always ask business partners if protobuf schema files are available Generate Go code using: protoc pb\xxx.</description></item><item><title>Application of AES Encryption Algorithm</title><link>https://www.shiguopeng.cn/en/posts/2022090716/</link><pubDate>Wed, 07 Sep 2022 16:52:05 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2022090716/</guid><description>Recently, I&amp;rsquo;ve been working on integrating third-party advertising bidding services. Most advertising platforms with bidding capabilities encrypt their bid prices using the AES algorithm.
When integrating with third parties, challenges arise due to varying encryption modes and the lack of SDKs (some only provide Java client code examples). Here are some practical approaches:
Use third-party validation tools like https://tool.lmeee.com/jiami/aes for cross-verification Analyze Java code to identify critical encryption parameters: Encryption Mode (ECB, CBC, CFB, OFB) Padding Method (pkcs5padding, pkcs7padding, zeropadding) Key Length (128-bit/8-char key, 192-bit/12-char key, 256-bit/16-char key) IV (Initialization Vector - some require random values, others use fixed values) Base64UrlSafe Encoding requirement for ciphertext Practical Observations: ECB Dominance: Many platforms use ECB mode for simplicity despite security risks, as it requires only a key (no IV).</description></item><item><title>Does Uploading a 10MB File in Go Really Use 10MB of Memory?</title><link>https://www.shiguopeng.cn/en/posts/2022070111/</link><pubDate>Fri, 01 Jul 2022 11:45:13 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2022070111/</guid><description>The short answer: It depends on your configuration and implementation.
Today I saw an interesting question in the community:
Why does PHP handle file uploads using move_uploaded_file to move a pre-uploaded file, rather than reading the file content directly from the HTTP Body?
This question intrigued me. After researching, I found an analysis of PHP file upload implementation (RFC1867) by Laruence (Bird Brother), but it didn&amp;rsquo;t fully explain the reason. So I decided to examine Go&amp;rsquo;s file upload implementation.</description></item><item><title>Service Registration and Discovery in Microservices</title><link>https://www.shiguopeng.cn/en/posts/2022061518/</link><pubDate>Wed, 15 Jun 2022 18:13:30 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2022061518/</guid><description>With service registration and discovery mechanisms, consumers don&amp;rsquo;t need to know the actual physical addresses of service providers to make calls, nor do they need to know how many providers are available. Service providers simply register with the registry to expose their services, without needing to know which specific services are consuming them.
RPC Configuration Name: user.rpc ListenOn: 0.0.0.0:8081 Etcd: Hosts: - 127.0.0.1:2379 Key: user.rpc Analyzing the etcd-related source code in go-zero.</description></item><item><title>Optimizing Database Queries to Reduce MySQL Load to 1%</title><link>https://www.shiguopeng.cn/en/posts/2022060916/</link><pubDate>Thu, 09 Jun 2022 16:59:31 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2022060916/</guid><description> Following the previous Redis incident, our monitoring system recently alerted about abnormal MySQL load in the advertising system The Ops team asked me to investigate whether recent code changes caused the database load spike. As shown: Database The graph clearly shows a sudden load surge at the marked timestamp, which persisted without subsiding Checking Git commit history revealed no deployments on that day, indicating operational configuration changes might be the culprit Accessed Alibaba Cloud&amp;rsquo;s SQL Audit and Analysis feature (similar solutions exist on other cloud platforms): SQL Audit The problematic SQL query was quickly identified, accounting for over 90% of total queries Next steps were straightforward: Locate the corresponding code for this SQL Root cause analysis: Original code handled single configurations, but recent operational changes allowed multiple options No caching implementation Optimized query logic and added caching mechanisms Database Database Post-optimization showed reduced database load, but another SQL query became prominent with higher average latency due to WHERE EXISTS usage: The Laravel whereHas method generated inefficient WHERE EXISTS queries GitHub solutions suggested using WHERE IN instead Implemented custom solution using these patterns (alternative packages available): laravel-wherehasin hasin eloquent-has-by-non-dependent-subquery Database Database Final optimizations resulted in: Balanced query distribution Database load reduced to 1% (compared to ~50% previously) Consistent performance during peak periods</description></item><item><title>YouMengji Launched on Google Play</title><link>https://www.shiguopeng.cn/en/posts/2022041514/</link><pubDate>Fri, 15 Apr 2022 14:41:25 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2022041514/</guid><description>A side note: The article description was auto-generated using https://copilot.github.com/. This tool is indeed very useful, everyone should give it a try. (The gray text in the image shows its auto-generated suggestions, press Tab to accept them) 1.png Preface In China, except for Huawei AppGallery, other app stores don&amp;rsquo;t allow individual developers to upload applications. Therefore, we decided to publish on Google Play. Initially when developing YouMengji, we didn&amp;rsquo;t consider internationalization and hardcoded all UI text.</description></item><item><title>Optimizing Redis Memory Usage for Ad Service: Reducing 30G+ Memory Footprint</title><link>https://www.shiguopeng.cn/en/posts/2022031610/</link><pubDate>Wed, 16 Mar 2022 10:09:52 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2022031610/</guid><description>Problem Analysis While reviewing legacy code, we discovered Redis operations without TTL settings. This likely occurred because:
Hash structures can&amp;rsquo;t set expiration time during creation Subsequent developers forgot to add expiration Common problematic patterns:
Date-based Hash keys
HSET xxx:ad_id:20220315 userid value Orphaned ad keys
HSET xxx:ad_id userid value (after ad campaign ended) Initial cluster status: 8-node cluster with 8GB/node, but actual usage reached 51G+
Memory overconsumption forced continuous resource scaling</description></item><item><title>[IoT] Raspberry Pi Pico Plays Music via Buzzer</title><link>https://www.shiguopeng.cn/en/posts/2022031522/</link><pubDate>Tue, 15 Mar 2022 22:19:56 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2022031522/</guid><description>Connecting a buzzer is relatively simple. You&amp;rsquo;ll need a buzzer module (I&amp;rsquo;m using an active/passive buzzer module).
Buzzer The buzzer has only three pins. Here&amp;rsquo;s the wiring reference:
Raspberry Pi Buzzer Note VUSB VCC 5V power (Pin 40) GP22 I/O GPIO pin GND GND Ground Found an arrangement of &amp;ldquo;Iron Blood Loyal Heart&amp;rdquo; online:
package main import ( &amp;#34;machine&amp;#34; &amp;#34;time&amp;#34; &amp;#34;tinygo.org/x/drivers/buzzer&amp;#34; ) type note struct { tone float64 duration float64 } func main() { // Note that 22 here is the I/O pin bzrPin := machine.</description></item><item><title>[IoT] Raspberry Pi Pico Lighting Up the Display</title><link>https://www.shiguopeng.cn/en/posts/2022031210/</link><pubDate>Sat, 12 Mar 2022 10:10:38 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2022031210/</guid><description>A craftsman must sharpen his tools to do his work well. First, let&amp;rsquo;s configure our development environment. Refer to the official TinyGo IDE integration guide: https://tinygo.org/docs/guides/ide-integration/ Using GoLand 2021 as our IDE, follow these steps: Install the TinyGo plugin: JetBrains Plugin Repository or search directly in File -&amp;gt; Settings -&amp;gt; Plugins After installation, configure the board type at File -&amp;gt; Settings -&amp;gt; Go -&amp;gt; TinyGo (select &amp;ldquo;pico&amp;rdquo; in this case) Restart GoLand 2021 to activate Pico-specific code completion TinyGo Plugin The display used in this project is a 0.</description></item><item><title>[IoT] Getting Started - Blinking the LED</title><link>https://www.shiguopeng.cn/en/posts/2022030917/</link><pubDate>Wed, 09 Mar 2022 17:59:04 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2022030917/</guid><description>Introduction As a complete novice in IoT development, after several days of online research, I learned that:
ESP32https://www.espressif.com/zh-hans/products/socs/esp32 is the king of cost-performance (built-in WiFi + Bluetooth) Raspberry Pi Pico is beginner-friendly and easy to blink LEDs To balance both cost-performance and ease of use, I bought both boards Both have official Taobao stores linked from their official websites: Raspberry Pi Espressif Systems Both boards cost around 20-30 RMB Windows Environment Variables Right-click Computer (or open any folder and right-click &amp;ldquo;This PC&amp;rdquo;) -&amp;gt; Properties -&amp;gt; Advanced System Settings -&amp;gt; Environment Variables -&amp;gt; Double-click PATH (System variables) -&amp;gt; Add new paths as needed Go Installation Download from https://golang.</description></item><item><title>Using laravel-s in Docker (Including Queue Usage)</title><link>https://www.shiguopeng.cn/en/posts/2022030118/</link><pubDate>Tue, 01 Mar 2022 18:12:32 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2022030118/</guid><description>Environment Configuration FROM phpswoole/swoole:php7.4-alpine # A script for installing PHP extensions COPY --from=mlocati/php-extension-installer /usr/bin/install-php-extensions /usr/local/bin/ RUN install-php-extensions pcntl redis pdo_mysql WORKDIR /var/www COPY . . RUN chmod -R 0777 storage &amp;amp;&amp;amp; \ chmod -R 0777 bootstrap/cache &amp;amp;&amp;amp; \ composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/ &amp;amp;&amp;amp; \ composer install --optimize-autoloader --no-dev &amp;amp;&amp;amp; \ php artisan config:cache &amp;amp;&amp;amp; \ php artisan route:cache &amp;amp;&amp;amp; \ php artisan view:cache &amp;amp;&amp;amp; \ php artisan laravels publish --no-interaction CMD [&amp;#34;php&amp;#34;, &amp;#34;bin/laravels&amp;#34;, &amp;#34;start&amp;#34;, &amp;#34;--env=product&amp;#34;] Deployment ## Build the image docker build .</description></item><item><title>Using gRPC</title><link>https://www.shiguopeng.cn/en/posts/2022022518/</link><pubDate>Fri, 25 Feb 2022 18:29:43 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2022022518/</guid><description>Preface There are many installation tutorials online. Due to updates in gRPC, many commands may become obsolete. This article reflects the current state at the time of writing. If you encounter issues, the best approach is to refer to the official documentation Installation First install Go Install the protoc compiler https://grpc.io/docs/protoc-installation/ The protoc compiler is used to compile .proto files containing service and message definitions Download the zip file matching your OS and architecture (e.</description></item><item><title>Advanced Usage of Pyroscope for Go and PHP Performance Analysis</title><link>https://www.shiguopeng.cn/en/posts/2022021516/</link><pubDate>Tue, 15 Feb 2022 16:23:40 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2022021516/</guid><description>Installation Many online tutorials simply use a single Docker command:
docker run -it -p 4040:4040 --restart=always pyroscope/pyroscope:latest server However, this basic installation lacks crucial configurations: no authentication for the data dashboard, no API reporting restrictions (e.g., limiting reporting via API keys), and no data persistence after container destruction. Here&amp;rsquo;s a better approach using docker-compose.yml: version: &amp;#34;3&amp;#34; services: pyroscope: image: &amp;#34;pyroscope/pyroscope:latest&amp;#34; ports: - &amp;#34;4040:4040&amp;#34; command: - &amp;#34;server&amp;#34; environment: ## Enforce API key authentication for data ingestion - PYROSCOPE_AUTH_INGESTION_ENABLED=true ## Enable login for web dashboard - PYROSCOPE_AUTH_INTERNAL_ENABLED=true volumes: ## Persistent data storage - .</description></item><item><title>Troubleshooting Laravel-S Memory Leak with Swoole Tracker</title><link>https://www.shiguopeng.cn/en/posts/2022010510/</link><pubDate>Wed, 05 Jan 2022 10:54:45 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2022010510/</guid><description>Environment Setup Built using swoole:alpine Docker image FROM phpswoole/swoole:php7.4-alpine RUN sed -i &amp;#39;s/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g&amp;#39; /etc/apk/repositories &amp;amp;&amp;amp; cat /etc/apk/repositories # Quick PHP extension installation COPY --from=mlocati/php-extension-installer /usr/bin/install-php-extensions /usr/local/bin/ RUN install-php-extensions pcntl redis pdo_mysql WORKDIR /var/www COPY . . RUN chmod -R 0777 storage &amp;amp;&amp;amp; \ chmod -R 0777 bootstrap/cache &amp;amp;&amp;amp; \ composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/ &amp;amp;&amp;amp; \ composer install --optimize-autoloader --no-dev &amp;amp;&amp;amp; \ php artisan config:cache &amp;amp;&amp;amp; \ php artisan route:cache &amp;amp;&amp;amp; \ php artisan view:cache &amp;amp;&amp;amp; \ php artisan laravels publish --no-interaction CMD [&amp;#34;php&amp;#34;, &amp;#34;bin/laravels&amp;#34;, &amp;#34;start&amp;#34;, &amp;#34;--env=product&amp;#34;] For initial setup, comment out the last two lines in Dockerfile: docker build .</description></item><item><title>Can Shaking Your Head Wake You Up from a Dream?</title><link>https://www.shiguopeng.cn/en/posts/2021111410/</link><pubDate>Sun, 14 Nov 2021 10:09:29 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2021111410/</guid><description>Preface I&amp;rsquo;ve encountered sleep paralysis multiple times, struggling to wake up until I found that shaking my head vigorously can break the spell.
Liu Cixin once said: &amp;ldquo;Imagination is an ability humans possess that seems like it should belong solely to gods. Its significance far exceeds our understanding.&amp;rdquo;
In dreams, your imagination becomes extraordinarily powerful.
The Dream It didn&amp;rsquo;t feel like a typical dream—I was fully conscious, even hearing voices outside the window clearly.</description></item><item><title>Building a Message Push Service Bot Using WeCom</title><link>https://www.shiguopeng.cn/en/posts/2021103013/</link><pubDate>Sat, 30 Oct 2021 13:57:42 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2021103013/</guid><description>Start Previously, I configured message push notifications on CODING for all successful project deployments. As the number of projects increased and other services required message notifications, the free quota provided by Server Chan became insufficient.
After researching two commonly used services, both have frequency limitations:
Server Chan: Free tier allows only 5 messages/day Qmsg Chan: 30 messages/day with occasional instability Configuration Discovered that Server Chan&amp;rsquo;s documentation teaches how to build a WeCom bot service.</description></item><item><title>Containerizing All Services: Running PHP Code in Containers with Laravel-S</title><link>https://www.shiguopeng.cn/en/posts/2021102416/</link><pubDate>Sun, 24 Oct 2021 16:05:45 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2021102416/</guid><description>Preface Recently containerized all Go programs on the server for deployment Combined with CODING&amp;rsquo;s CI/CD, deployment has become extremely pleasant But there were still several PHP projects remaining on the server Blog (Originally built with WordPress) Deploy Nginx and PHP containers, then reverse proxy via host machine Discovered Hugo (similar to Hexo), a static site generator Migrated blog to Hugo with fast builds and real-time previews Now runs in a single Nginx container with host reverse proxy Details: My Blog DreamNote Admin (Laravel) Original Nginx + PHP-FPM container approach Switched to persistent PHP runtime using laravel-s (supports dcat-admin) Official Swoole container docker-swoole with custom Dockerfile: FROM phpswoole/swoole:php7.</description></item><item><title>Blog Self-Description</title><link>https://www.shiguopeng.cn/en/posts/2021102110/</link><pubDate>Thu, 21 Oct 2021 10:53:14 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2021102110/</guid><description>Now The blogging workflow is simple - after local writing, pushing code to CODING triggers full pipeline automation: Start local hugo server for writing Push to CODING for CI/CD (reference: Continuous Integration for Projects) Generate public directory using ubuntu image Package into nginx:alpine container (extremely lightweight) After build completion: Build plan deploys to server Container restarts Notification sent for successful deployment Step3 (2021-10-22) Switched to hugo (similar to hexo but written in Go instead of Node.</description></item><item><title>Continuous Integration for Go Projects with CODING</title><link>https://www.shiguopeng.cn/en/posts/2021101416/</link><pubDate>Thu, 14 Oct 2021 16:59:36 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2021101416/</guid><description>https://coding.net/ provides 1000 minutes of free build resources per month
Read the documentation first: https://help.coding.net/docs/ci/start.html Start Developed using https://github.com/gogf/gf. Modified its default Dockerfile (original requires host machine compilation for dependency caching; modified to perform all operations within the image). ############################################################################### # Use first-stage image for building ############################################################################### FROM golang as builder ENV GO111MODULE=on \ GOPROXY=https://goproxy.cn,direct WORKDIR /app COPY . . RUN go mod tidy # Modified for CGO dependency: CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -ldflags &amp;#39;-extldflags &amp;#34;-static&amp;#34;&amp;#39; -o main main.</description></item><item><title>Flutter Integration with Umeng: A Step-by-Step Record</title><link>https://www.shiguopeng.cn/en/posts/2021091800/</link><pubDate>Sat, 18 Sep 2021 00:29:53 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2021091800/</guid><description>Integrating Umeng is a huge pitfall for non-Android developers. Here&amp;rsquo;s my experience with some common pitfalls like UMConfigure not found, incorrect override syntax in Kotlin (official docs use Java), and misleading official plugins. The actual process is simple:
Start with native integration first - even for Flutter apps. Follow Android integration steps before using any Flutter plugin. Official documentation: Umeng Android Integration Guide (replace if link expires) Always use maven automatic integration (repeat 3x) for non-native developers Native Setup in 3 Steps Dependency configuration</description></item><item><title>MySQL Partitioning Practice</title><link>https://www.shiguopeng.cn/en/posts/2021082715/</link><pubDate>Fri, 27 Aug 2021 15:46:03 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2021082715/</guid><description>While I&amp;rsquo;ve read many related articles before, true understanding comes from practice. Recently, the data team restructured logging formats. I designed a table schema and asked them to write cleaned client logs into it. As this is a video playback statistics table, we implemented date-based partitioning. With less than 100k videos in the library, we opted for monthly partitioning instead of daily. For auto-increment primary key id, you must create composite primary key with partitioning key In our actual implementation, we simply omitted the primary key `id` BIGINT UNSIGNED NOT NULL auto_increment, PRIMARY KEY(`id`, `date_key`) Partition by month Other playback statistics fields are omitted Records before 2021-09-01 will be stored in p_202108 partition Records from 2021-09-01 to 2021-09-30 will go to p_202109 partition CREATE TABLE `video_play_logs` ( `video_id` INT UNSIGNED NOT NULL, `date_key` date NOT NULL, index `video_play_logs_video_id_index` ( `video_id` ) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci PARTITION BY RANGE(to_days(`date_key`)) ( PARTITION p_202108 VALUES LESS THAN (to_days(&amp;#39;20210901&amp;#39;)), PARTITION p_202109 VALUES LESS THAN (to_days(&amp;#39;20211001&amp;#39;)), PARTITION p_202110 VALUES LESS THAN (to_days(&amp;#39;20211101&amp;#39;)), PARTITION p_202111 VALUES LESS THAN (to_days(&amp;#39;20211201&amp;#39;)), PARTITION p_202112 VALUES LESS THAN (to_days(&amp;#39;20220101&amp;#39;)) ) Verify partition configuration Insert test data and check TABLE_ROWS for record counts in each partition SELECT TABLE_NAME, PARTITION_NAME, TABLE_ROWS FROM information_schema.</description></item><item><title>Analyzing How GoFrame Dynamically Loads Configuration Files and the Invocation of runtime.Caller</title><link>https://www.shiguopeng.cn/en/posts/2021082518/</link><pubDate>Wed, 25 Aug 2021 18:47:28 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2021082518/</guid><description>According to the official documentation:
Default Directory Configuration
When initializing the gcfg configuration management object, it automatically adds the following configuration file search directories by default:
Current working directory and its config subdirectory: e.g., /home/www and /home/www/config when working in /home/www Executable file directory and its config subdirectory: e.g., /tmp and /tmp/config for a binary in /tmp Main package directory and its config subdirectory (only effective in source development): e.g., /home/john/workspace/gf-app and /home/john/workspace/gf-app/config for a main package in that directory During development, the configuration file can always be found correctly through the main package location regardless of binary relocation.</description></item><item><title>A Bug When Using defer in Loops in Go</title><link>https://www.shiguopeng.cn/en/posts/2021081013/</link><pubDate>Tue, 10 Aug 2021 13:47:50 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2021081013/</guid><description>First note: Using defer inside loops is generally considered a bad practice
Came across this issue while browsing the community: package main import &amp;#34;fmt&amp;#34; type Test struct { name string } func (t *Test) Close() { fmt.Println(t.name, &amp;#34; closed&amp;#34;) } func main() { ts := []Test{{&amp;#34;a&amp;#34;}, {&amp;#34;b&amp;#34;}, {&amp;#34;c&amp;#34;}} for _, t := range ts { defer t.Close() } } // Output: // c closed // c closed // c closed The output shows three c closed results.</description></item><item><title>PHP Source Code Reading</title><link>https://www.shiguopeng.cn/en/posts/2021080310/</link><pubDate>Tue, 03 Aug 2021 10:51:57 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2021080310/</guid><description>Getting Started (Environment Setup) Create a project directory and add Dockerfile FROM centos:7 # Install dependencies RUN yum -y install gcc gcc-c++ gdb autoconf libjpeg libjpeg-devel libpng libpng-devel freetype freetype-devel libxml2 libxml2-devel zlib zlib-devel glibc glibc-devel glib2 glib2-devel bzip2 bzip2-devel ncurses ncurses-devel curl curl-devel e2fsprogs e2fsprogs-devel krb5 krb5-devel libidn libidn-devel openssl openssl-devel openldap openldap-devel nss_ldap openldap-clients openldap-servers gd gd2 gd-devel gd2-devel perl-CPAN pcre-devel libicu-devel wget # Download specific PHP version RUN wget -O /tmp/php.</description></item><item><title>A Slow API Incident Leading to Database Query Testing and Fully Automated API Test Assertions</title><link>https://www.shiguopeng.cn/en/posts/2021072215/</link><pubDate>Thu, 22 Jul 2021 15:08:54 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2021072215/</guid><description>Today during client-side testing, feedback indicated a slow API response. With the responsible colleague on leave, I investigated the project and confirmed the issue.
Added SQL logging in the controller: # SQL logging DB::listen(fn(QueryExecuted $query) =&amp;gt; Log::info($query-&amp;gt;sql)); # Log output [2021-07-22 12:46:15] local.INFO: select * from `albums` where `albums`.`id` = ? and `albums`.`deleted_at` is null limit 1 ... (repeated 24 times) The logs revealed multiple identical queries - a classic N+1 problem caused by missing eager loading Database query pseudocode: class Controller { public function index() { $models = Model::query()-&amp;gt;limit(20)-&amp;gt;get(); return ModelsResource::collection($models); } } class ModelsResource extends JsonResource { public function toArray($request) { return [ &amp;#39;id&amp;#39; =&amp;gt; $this-&amp;gt;id, &amp;#39;name&amp;#39; =&amp;gt; $this-&amp;gt;title, &amp;#39;album_id&amp;#39; =&amp;gt; $this-&amp;gt;album_id, // Problematic line &amp;#39;album_name&amp;#39; =&amp;gt; $this-&amp;gt;album-&amp;gt;title, ]; } } The resource accessed the album relationship without eager loading Solution: Add eager loading $models = Model::query()-&amp;gt;with(&amp;#39;album&amp;#39;)-&amp;gt;limit(20)-&amp;gt;get(); Prevention Strategies Problem detection is costly - better to prevent through automation Implemented HTTP testing with SQL query monitoring in base TestCase: public function json($method, $uri, array $data = [], array $headers = []) { $maxCount = 10; DB::enableQueryLog(); $response = parent::json($method, $uri, $data, $headers); $queries = collect(DB::getQueryLog())-&amp;gt;pluck(&amp;#39;query&amp;#39;); $this-&amp;gt;assertLessThan( $maxCount, $queries-&amp;gt;count(), sprintf(&amp;#34;Endpoint:%s[%s], SQL:%d\r\n%s&amp;#34;, $uri, $method, $maxCount, $queries-&amp;gt;implode(&amp;#34;\r\n&amp;#34;)) ); DB::flushQueryLog(); return $response; } Enhanced validation using unique query comparison: $duplicateQueries = $queries-&amp;gt;count() - $queries-&amp;gt;unique()-&amp;gt;count(); $this-&amp;gt;assertLessThan($maxDuplicates, $duplicateQueries, &amp;#34;Excessive duplicate queries&amp;#34;); Route coverage validation via custom test suite: &amp;lt;testsuite name=&amp;#34;End&amp;#34;&amp;gt; &amp;lt;file&amp;gt;tests/EndApiTest.</description></item><item><title>Using Git flow in Sourcetree</title><link>https://www.shiguopeng.cn/en/posts/2021072112/</link><pubDate>Wed, 21 Jul 2021 12:12:09 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2021072112/</guid><description>First, let&amp;rsquo;s look at the Git flow diagram:
Git flow The flowchart might seem complex at first glance. We&amp;rsquo;ll use Sourcetree to help understand the process. Getting Started (Screenshots show Sourcetree operations, commands show actual execution) Create a new project log-service mkdir log-service cd log-service git init Sourcetree Initialize project configuration Set up framework selection, project description, etc. Replace the following commands with your actual operations: echo &amp;#34;## log-service&amp;#34; &amp;gt; README.</description></item><item><title>Solving Custom Page Refresh Issue with Admin PJAX by Breaking Out of Conventional Thinking</title><link>https://www.shiguopeng.cn/en/posts/2021070713/</link><pubDate>Wed, 07 Jul 2021 13:04:58 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2021070713/</guid><description>Using laravel-admin for backend development, we added a notification bell in the top-right corner Laravel Admin Notification Interface As shown above, clicking the bell icon should clear notifications and refresh the current page. Implemented using laravel-admin&amp;rsquo;s action: &amp;lt;?php namespace App\Admin\Actions\Custom; use Encore\Admin\Actions\Action; use Illuminate\Http\Request; class MarkNotificationRead extends Action { protected $selector = &amp;#39;.mark-notification-read&amp;#39;; public function handle(Request $request) { // forget notifications return $this-&amp;gt;response()-&amp;gt;success(&amp;#34;Marked all as read&amp;#34;)-&amp;gt;refresh(); } public function html() { // get notifications $count = 1; $countText = &amp;#34;&amp;lt;span class=\&amp;#34;label label-danger\&amp;#34;&amp;gt;{$count}&amp;lt;/span&amp;gt;&amp;#34;; return &amp;#34;&amp;lt;li title=&amp;#39;Click to mark as read&amp;#39;&amp;gt; &amp;lt;a href=\&amp;#34;#\&amp;#34; class=&amp;#39;mark-notification-read&amp;#39;&amp;gt; &amp;lt;i data-count=&amp;#39;{$count}&amp;#39; id=&amp;#39;notification&amp;#39; class=\&amp;#34;fa fa-bell fa-rotate-0\&amp;#34;&amp;gt;&amp;lt;/i&amp;gt; {$countText} &amp;lt;/a&amp;gt; &amp;lt;/li&amp;gt;&amp;#34;; } } The pseudo-code above implements the notification feature.</description></item><item><title>A Bug Caused by Static Variables in Laravel Queues</title><link>https://www.shiguopeng.cn/en/posts/2021070612/</link><pubDate>Tue, 06 Jul 2021 12:43:13 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2021070612/</guid><description>Environment PHP_VERSION=7.4 laravel/framework: ^7.0 Static Variables In many programming languages, static variables are defined as variables that: Have the same lifecycle as the program Are initialized only once However, in PHP&amp;rsquo;s common runtime environment (php-fpm mode), processes get recycled after each request, so static variables don&amp;rsquo;t persist in memory (only effective during the current request) Official PHP documentation states: &amp;ldquo;Another important feature of variable scoping is the static variable. A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.</description></item><item><title>A Lesson Learned from Laradock Cron Job Failures</title><link>https://www.shiguopeng.cn/en/posts/2021070211/</link><pubDate>Fri, 02 Jul 2021 11:25:44 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2021070211/</guid><description>Debugging Steps The cron jobs in laradock are executed in the workspace container. Check logs using: docker-compose logs -f workspace Sample log output:
Jul 2 12:26:59 9b6ec4d18dd1 syslog-ng[12]: syslog-ng starting up; version=&amp;#39;3.13.2&amp;#39; workspace_1 | *** Booting runit daemon... workspace_1 | *** Runit started as PID 20 workspace_1 | Jul 2 12:27:00 9b6ec4d18dd1 cron[23]: (CRON) INFO (pidfile fd = 3) ... Enter the container: docker-compose exec workspace bash Test cron job execution without suppressing output: /usr/bin/php /var/www/artisan schedule:run Permission Issues Logs in /storage/logs showed permission errors when created by root user.</description></item><item><title>How to Remove the Core Service - Views in Laravel</title><link>https://www.shiguopeng.cn/en/posts/2021052616/</link><pubDate>Wed, 26 May 2021 16:54:46 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2021052616/</guid><description>Previous article: Speed Up Your Service Performance by Reducing Service Provider Boot Time 2.0 A reader mentioned errors when directly removing the View service. This article demonstrates how to properly remove the View service. Step-by-Step Guide 1. Create a New Laravel Project composer create-project laravel/laravel=7.* laravel-demo 2. Modify the Default Route Edit routes/web.php to return JSON instead of a view:
Route::get(&amp;#39;/&amp;#39;, function () { return [ &amp;#39;code&amp;#39; =&amp;gt; 200, &amp;#39;msg&amp;#39; =&amp;gt; &amp;#39;hello&amp;#39; ]; }); 3.</description></item><item><title>Optimizing Laravel Performance by Reducing Service Providers Boot 2.0</title><link>https://www.shiguopeng.cn/en/posts/2021052512/</link><pubDate>Tue, 25 May 2021 12:08:42 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2021052512/</guid><description>Performance has always been one of the most discussed topics in Laravel, yet it has brought fresh perspectives to many PHP developers. Let&amp;rsquo;s optimize this framework once again.
Fundamentals (Common Knowledge) Use Redis drivers for caching, sessions, and queues Framework built-in caching: Route caching: php artisan route:cache Configuration caching: php artisan config:cache Implement caching based on API idempotency Upgrades OPcache: Enable it without hesitation Set opcache.validate_timestamps=0 to prevent automatic code updates in production (similar to compiled languages).</description></item><item><title>Learning Go's Plan 9 Assembly</title><link>https://www.shiguopeng.cn/en/posts/2021051118/</link><pubDate>Tue, 11 May 2021 18:33:55 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2021051118/</guid><description>For beginners, I recommend these introductory tutorials first:
Assembly Language Quick Start
Assembly Language Primer (Ruan Yifeng) Be sure to read Mr. Ruan&amp;rsquo;s tutorial in detail Common Identifiers (See Registers and Operation Instructions tables at the end for more) $ prefix followed by numbers represents a constant value FUNCDATA and PCDATA instructions contain garbage collector information generated by the compiler PCDATA syntax: PCDATA tableid, tableoffset PCDATA has two parameters: table type and table offset.</description></item><item><title>Cross-Service Data Verification Using AES Algorithm</title><link>https://www.shiguopeng.cn/en/posts/2021051112/</link><pubDate>Tue, 11 May 2021 12:41:39 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2021051112/</guid><description>Recently while working on an advertising service that requires cross-application data transmission between backend services (PHP + Go), we chose symmetric encryption for implementation.
Common Pitfalls Key Length Errors may occur if using a 32-bit key (since documentation states valid lengths are 16, 24, 32)
AES-128: Requires 16-byte key
AES-192: Requires 24-byte key
AES-256: Requires 32-byte key
Always match key length to the selected algorithm.
Padding Algorithm Easily overlooked in PHP due to simple usage: $text = &amp;#34;String to encrypt&amp;#34;; // Key length must match algorithm requirements $key = &amp;#34;2bfbd593bb32b2b9&amp;#34;; // AES-128-ECB depends on chosen algorithm openssl_encrypt($text, &amp;#39;AES-128-ECB&amp;#39;, $key); The above produces base64-encoded output by default.</description></item><item><title>SSH-Keygen Generated Keys Cannot Be Used for Remote Connections, Sourcetree Unable to Operate Remote Repositories</title><link>https://www.shiguopeng.cn/en/posts/2021031916/</link><pubDate>Fri, 19 Mar 2021 16:23:36 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2021031916/</guid><description>Xshell Recently, using the command:
ssh-keygen to generate a private key could not be imported into Xshell for use.
ssh-keygen Use the following new command to generate keys:
rsa indicates using RSA encryption
ssh-keygen -m PEM -t rsa Sourcetree If keys are configured but Sourcetree consistently fails to operate remote repositories Go to Tools -&amp;gt; Options -&amp;gt; General
Sourcetree Select OpenSSH and choose the id_rsa private key under your user directory.</description></item><item><title>A Bug Caused by Combined Array Index Changes and Reference Parameters in PHP</title><link>https://www.shiguopeng.cn/en/posts/2021031412/</link><pubDate>Sun, 14 Mar 2021 12:07:42 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2021031412/</guid><description>Today, our team encountered a bug reported in the group chat. After cloning the project locally, I spent some time reproducing the issue.
Code Overview The following code causes the first item removal to convert a Collection into an object (JSON data): protected function transformJson($items) { return Collection::make($items) - -&amp;gt;values() -&amp;gt;where(&amp;#39;_remove_&amp;#39;, &amp;#39;0&amp;#39;) + -&amp;gt;values() -&amp;gt;map(fn($item) =&amp;gt; Arr::except($item, &amp;#39;_remove_&amp;#39;)) -&amp;gt;toJson(); In the API data retrieval logic, this function call pattern caused issues: public function index() { // $json={&amp;#34;1&amp;#34;:{&amp;#34;id&amp;#34;: 2}} $data = Collection::make($json); // Filtering converts indexes to 0-based $index = $this-&amp;gt;getRandomAd($data, [1]); // Returns null due to original key mismatch return $data-&amp;gt;get($index); } protected function getRandomAd(Collection $data, $notIn=[]) { $index = -1; if (count($notIn) &amp;gt; 0) { $data = $data-&amp;gt;filter(fn($item) =&amp;gt; !</description></item><item><title>I Have a Technique Called Quick Sort</title><link>https://www.shiguopeng.cn/en/posts/2021012915/</link><pubDate>Fri, 29 Jan 2021 15:24:18 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2021012915/</guid><description>Recently while solving a problem on LeetCode (finding the kth largest number), I needed to sort an array. Realized I only knew basic sorting algorithms like Bubble Sort and Insertion Sort. Then I reviewed Quick Sort through animated examples online, and implemented my own version (code is similar to common implementations): // 1. Select a pivot element (can choose the first element or random element) // 2. Use two pointers starting from both ends, right pointer moves first // 3.</description></item><item><title>Stop Words and Custom Dictionaries in Elasticsearch</title><link>https://www.shiguopeng.cn/en/posts/2021011316/</link><pubDate>Wed, 13 Jan 2021 16:12:02 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2021011316/</guid><description>Today, our product team reported an issue: why can&amp;rsquo;t we find relevant data when searching for &amp;ldquo;be&amp;rdquo; in our system? There are indeed videos containing phrases like &amp;ldquo;i want to be xxx&amp;rdquo; in our database Stop Words We use the IK Analyzer. After checking GitHub issues, we learned about stop words. Reference: Stop words explanation
Solution: Remove the specific stop word
Navigate to Elasticsearch root directory (Docker container in my case) cd /usr/share/elasticsearch Access IK Analyzer configuration (located in config directory for newer versions) cd config/analysis-ik Check the English stop words file: # cat stopword.</description></item><item><title>Differences Between Go and PHP and Parameter Passing in Context</title><link>https://www.shiguopeng.cn/en/posts/2021010814/</link><pubDate>Fri, 08 Jan 2021 14:55:21 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2021010814/</guid><description>For developers transitioning from PHP, some common questions arise: How can sequential requests affect each other? In many programming languages, this could be easily achieved using global variables However, in PHP, each request is completely independent This design has both advantages and disadvantages: Downside: Requires reloading code and configurations on each request Advantage: Automatic memory cleanup after request completion eliminates leakage concerns While PHP can achieve cross-request effects using tools like Redis, the approaches differ fundamentally Sample Go Code Analysis package main import ( &amp;#34;fmt&amp;#34; &amp;#34;github.</description></item><item><title>Today Completed Refactoring All Internal APIs from PHP to Go</title><link>https://www.shiguopeng.cn/en/posts/2021010613/</link><pubDate>Wed, 06 Jan 2021 13:00:27 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2021010613/</guid><description>Previous API Request Flow User opens APP and requests business API Business API requests recommendation algorithm (with fault tolerance) Recommendation algorithm requests internal service Internal service provides business interface data to recommendation algorithm (e.g., manually configured recommendations) user -&amp;gt; API -&amp;gt; recommend service -&amp;gt; inner service user &amp;lt;- API &amp;lt;- recommend service &amp;lt;- inner service Originally built with Laravel, both API and inner service faced a single-point bottleneck. While API servers could scale horizontally, the inner service remained single-node.</description></item><item><title>Why Timestamp in MySQL Handles Time Zones Automatically</title><link>https://www.shiguopeng.cn/en/posts/2020120917/</link><pubDate>Wed, 09 Dec 2020 17:30:25 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2020120917/</guid><description>I&amp;rsquo;ve long been curious why MySQL&amp;rsquo;s timestamp type can effortlessly handle time zone issues. In practical use with Laravel frameworks, Migration files default to timestamp fields without requiring special attention.
Getting Started Check current database time zone settings mysql&amp;gt; show variables like &amp;#34;%time_zone%&amp;#34;; +------------------+--------+ | Variable_name | Value | +------------------+--------+ | system_time_zone | CST | | time_zone | +08:00 | +------------------+--------+ 2 rows in set (0.30 sec) View table structure mysql&amp;gt; desc timestamp_test; +--------------+-----------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------------+-----------+------+-----+---------+----------------+ | id | int | NO | PRI | NULL | auto_increment | | created_time | datetime | YES | | NULL | | | created_at | timestamp | YES | | NULL | | +--------------+-----------+------+-----+---------+----------------+ 3 rows in set (0.</description></item><item><title>Elasticsearch Search Ranking Issues Caused by Different Tokenizers</title><link>https://www.shiguopeng.cn/en/posts/2020113022/</link><pubDate>Mon, 30 Nov 2020 22:51:55 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2020113022/</guid><description>When implementing Chinese search, many developers naturally use the ik tokenizer plugin from GitHub A common mapping configuration following official documentation examples looks like this: { &amp;#34;properties&amp;#34;: { &amp;#34;title&amp;#34;: { &amp;#34;type&amp;#34;: &amp;#34;text&amp;#34;, &amp;#34;analyzer&amp;#34;: &amp;#34;ik_max_word&amp;#34;, &amp;#34;search_analyzer&amp;#34;: &amp;#34;ik_smart&amp;#34; } } } Let&amp;rsquo;s examine data in a test index containing two documents: &amp;ldquo;打火车&amp;rdquo; (beat train) and &amp;ldquo;火车&amp;rdquo; (train) curl 127.0.0.1:9200/test/_search | jq { &amp;#34;took&amp;#34;: 1, &amp;#34;timed_out&amp;#34;: false, &amp;#34;_shards&amp;#34;: { &amp;#34;total&amp;#34;: 1, &amp;#34;successful&amp;#34;: 1, &amp;#34;skipped&amp;#34;: 0, &amp;#34;failed&amp;#34;: 0 }, &amp;#34;hits&amp;#34;: { &amp;#34;total&amp;#34;: { &amp;#34;value&amp;#34;: 2, &amp;#34;relation&amp;#34;: &amp;#34;eq&amp;#34; }, &amp;#34;max_score&amp;#34;: 1, &amp;#34;hits&amp;#34;: [ { &amp;#34;_index&amp;#34;: &amp;#34;test&amp;#34;, &amp;#34;_type&amp;#34;: &amp;#34;_doc&amp;#34;, &amp;#34;_id&amp;#34;: &amp;#34;Video_1&amp;#34;, &amp;#34;_score&amp;#34;: 1, &amp;#34;_source&amp;#34;: { &amp;#34;id&amp;#34;: 1, &amp;#34;title&amp;#34;: &amp;#34;打火车&amp;#34; } }, { &amp;#34;_index&amp;#34;: &amp;#34;test&amp;#34;, &amp;#34;_type&amp;#34;: &amp;#34;_doc&amp;#34;, &amp;#34;_id&amp;#34;: &amp;#34;Video_2&amp;#34;, &amp;#34;_score&amp;#34;: 1, &amp;#34;_source&amp;#34;: { &amp;#34;id&amp;#34;: 2, &amp;#34;title&amp;#34;: &amp;#34;火车&amp;#34; } } ] } } Searching for &amp;ldquo;打火车&amp;rdquo; yields unexpected ranking: curl 127.</description></item><item><title>Code Style and Quality Control in PHP Projects</title><link>https://www.shiguopeng.cn/en/posts/2020110215/</link><pubDate>Mon, 02 Nov 2020 15:32:57 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2020110215/</guid><description>Maintaining consistent code style is crucial in team development Configure PSR12 style in PHPStorm File -&amp;gt; Settings -&amp;gt; Editor-&amp;gt; Code Style -&amp;gt; Set from -&amp;gt; select PSR12 PhpStorm PSR12 Code Style Settings Using PHP_CodeSniffer for Code Style Checks Create phpcs.xml in project root for team-wide usage
Configuration notes:
Official documentation is limited - often requires debugging error messages Example: To disable end xxx() comments: Search source code for //end Locate PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting::ClosingDeclarationCommentSniff Remove &amp;lt;rule ref=&amp;quot;Squiz.</description></item><item><title>Making Concurrent Requests in PHP</title><link>https://www.shiguopeng.cn/en/posts/2020061715/</link><pubDate>Wed, 17 Jun 2020 15:04:16 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2020061715/</guid><description>PHP has always operated with a page-level lifecycle, where variables from previous requests aren&amp;rsquo;t shared with subsequent ones (unlike resident memory languages).
Most PHP code executes sequentially from top to bottom without callback capabilities The curl_multi_* function family enables &amp;ldquo;multi-threaded&amp;rdquo;-like behavior in PHP Recommended library for easier implementation: https://github.com/php-curl-class/php-curl-class Official concurrent request demo
&amp;lt;?php require __DIR__ . &amp;#39;/../vendor/autoload.php&amp;#39;; use Curl\MultiCurl; $urls = array( &amp;#39;tag3&amp;#39; =&amp;gt; &amp;#39;https://httpbin.org/post&amp;#39;, &amp;#39;tag4&amp;#39; =&amp;gt; &amp;#39;https://httpbin.org/get&amp;#39;, &amp;#39;tag5&amp;#39; =&amp;gt; &amp;#39;https://httpbin.</description></item><item><title>Sorting Algorithm - Bucket Sort</title><link>https://www.shiguopeng.cn/en/posts/2020060709/</link><pubDate>Sun, 07 Jun 2020 09:28:23 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2020060709/</guid><description>Bucket Sort is well-suited for sorting numbers in the range of 0~100, but its efficiency decreases when dealing with data that has a wide value range.
Algorithm Steps Create n empty buckets based on requirements Traverse the input array to find the maximum and minimum values For each element num, calculate bucket index using formula: floor((num - min) / n) If a bucket already contains elements, maintain elements in sorted order (using linked list) Repeat steps 3-4 until all elements are distributed Concatenate all buckets&amp;rsquo; linked lists and output the sorted array package main import ( &amp;#34;fmt&amp;#34; &amp;#34;math&amp;#34; ) func main() { data := []int{111, 9, 2, 4, 9, 3, 3, 5, 7, 1, 8, 2, 11, 22, 99, 192} fmt.</description></item><item><title>Getting Started with Docker and Docker-Compose</title><link>https://www.shiguopeng.cn/en/posts/2020060311/</link><pubDate>Wed, 03 Jun 2020 11:40:39 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2020060311/</guid><description>Many introductory articles are available online. I found these three particularly beginner-friendly:
Docker Tutorial Series from Basics to Advanced
Docker Tutorial Series (2): Docker Build
Docker Tutorial Series (3): Docker-Compose Docker You can directly pull an image using the command (take nginx as an example): docker pull nginx Dockerfile Essentially a text file describing how an image is built. After writing a Dockerfile, execute docker build to construct the image based on the instructions.</description></item><item><title>Install php-rdkafka Extension and Use Kafka for Logging</title><link>https://www.shiguopeng.cn/en/posts/2020050815/</link><pubDate>Fri, 08 May 2020 15:54:20 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2020050815/</guid><description>Recently, the user logs in our project have reached hundreds of millions. For convenience, we previously stored them directly in MySQL. Now big data requirements are pushing us to migrate these logs to Kafka.
Installation Development Environment Considerations Windows for local development Non-compiled installation for testing environment Production environment maintained by Ops team Linux Installation Ensure pecl is installed: pecl help version Install via pecl: sudo pecl install rdkafka Compile from Source Install dependencies (requires librdkafka):</description></item><item><title>Using Decay Functions in ElasticSearch to Perfect Your Search Results</title><link>https://www.shiguopeng.cn/en/posts/2020042718/</link><pubDate>Mon, 27 Apr 2020 18:18:12 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2020042718/</guid><description>A recent project required enhancements to existing search functionality:
Elasticsearch 7.6 (Note: parameters may vary across major versions) Original search: Simple full-text indexing of title + body content
New requirements: Improve result sorting based on multiple factors - publication date (older content should score lower), manually assigned weight values (higher is better), and popularity metrics.
After researching the documentation, we found Elasticsearch natively supports this through Decay Functions.
Elasticsearch&amp;rsquo;s built-in decay functions work with numeric, date, and geo fields.</description></item><item><title>Method for Batch Downloading and Packaging Files from Remote URLs</title><link>https://www.shiguopeng.cn/en/posts/2020042318/</link><pubDate>Thu, 23 Apr 2020 18:56:21 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2020042318/</guid><description>Background Recently encountered a problem during code refactoring: needing to batch download and package a set of images from OSS The old server directly mounted OSS to the filesystem, using Linux commands for copying and packaging (fast but incompatible with the new server architecture) OSS doesn&amp;rsquo;t provide direct packaging APIs (Qiniu Cloud supports this) Solutions Considered Discarded PHP backend fetching images to memory for packaging (memory overload risk with AI/PSD files) Discarded PHP backend saving images to disk for packaging (slow fetching and processing for large files) Implemented Frontend solution: JS fetches file info from backend, asynchronously downloads resources, and packages them client-side Prerequisites CORS configuration: Requires adding cross-origin headers on OSS/resource server CDN bypass: Configure a dedicated domain without CDN acceleration (skip if not using CDN) Implementation Steps Use JSZip library for client-side zip operations Utilize JSZip-utils for handling remote resource fetching Core implementation logic: &amp;lt;!</description></item><item><title>Using Lookahead and Lookbehind Assertions in Regular Expressions to Format Your Text</title><link>https://www.shiguopeng.cn/en/posts/2020011914/</link><pubDate>Sun, 19 Jan 2020 14:52:43 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2020011914/</guid><description>Given the following string:
let str = &amp;#39;为中华\n\n只崛aaa起\n而读书\n 我是123中国1111人&amp;#39;; Desired Formatting Effects Auto-indent with 4 spaces after each line break Add spacing between numbers and other characters Add spacing between letters and other characters Idempotent formatting (repeated formatting won&amp;rsquo;t cause inconsistencies) Implementation code:
// Lookahead assertion to ensure no 4 spaces follow const brReg = /\n(?!\s{4})/g; // Lookbehind assertion to check preceding characters const numPreReg = /(?&amp;lt;!\s|\d)(\d+)/g; const numExtReg = /(\d+)(?</description></item><item><title>Fake Requests in Slim for Your HTTP Testing Needs</title><link>https://www.shiguopeng.cn/en/posts/2019120417/</link><pubDate>Wed, 04 Dec 2019 17:21:20 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2019120417/</guid><description>When needing HTTP testing in code, Laravel has built-in functionality for this. With Slim, we have to build our own solution. After searching online for examples and finding limited resources, I decided to examine Laravel&amp;rsquo;s source code for inspiration. Discovered that the core idea is to mock a Request object and execute it to get response results. Implemented this approach in Slim framework accordingly. Setting Up Test Files Add autoload configuration in composer.</description></item><item><title>Using Middleware for Request Caching in Slim4</title><link>https://www.shiguopeng.cn/en/posts/2019112812/</link><pubDate>Thu, 28 Nov 2019 12:39:39 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2019112812/</guid><description>When developing web pages or API interfaces, we often encounter the following scenario:
A request is processed by querying the database and returning transformed data Some pages/interfaces with infrequent data changes (e.g. homepage) may experience performance issues under high traffic Solution: Cache processed content in storage like Redis before returning the response Subsequent requests first check the cache - return immediately if valid If cache expires, repeat steps [3-4] Here&amp;rsquo;s an implementation in Slim4 framework:</description></item><item><title>Slim - PHP - Laravel Performance Test</title><link>https://www.shiguopeng.cn/en/posts/2019112515/</link><pubDate>Mon, 25 Nov 2019 15:32:13 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2019112515/</guid><description>Test Environment Local Configuration (Win 10 i7-8565U 16G)(Nginx 1.15.11)(MySQL 5.5.62) Cloud Server (1 Core 2G)(Nginx 1.16.1)(MySQL 5.5.62) Performance Results Software Database Model Local QPS Cloud Server QPS Laravel 6.3.0 (with session) ORM 12.11 5.15 Laravel 6.3.0 (with session) PDO 13.85 5.31 Laravel 6.3.0 ORM 13.06 5.69 Laravel 6.3.0 PDO 13.98 5.89 Slim 4.3.0 PDO 41.04 43.65 PHP 7.1.9 Native PDO 52.85 51.81 Notes All tests performed using ApacheBench (ab) with command:</description></item><item><title>Implementation of Coupon Functionality</title><link>https://www.shiguopeng.cn/en/posts/2019090423/</link><pubDate>Wed, 04 Sep 2019 23:06:17 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2019090423/</guid><description>Recently I&amp;rsquo;ve developed several e-commerce projects, which inevitably involved designing coupon systems.
Since the Monday Mall project didn&amp;rsquo;t have this module, I decided to implement it during this period.
Referencing JD.com&amp;rsquo;s style, created a template like this:
Coupon Here&amp;rsquo;s the core logic:
First, we need a coupon template table Stores coupon templates for backend generation and user redemption Requires a separate user coupon table Table structure overview:
Coupon # Template Table `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `title` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT &amp;#39;Coupon title&amp;#39;, `amount` decimal(8,2) NOT NULL COMMENT &amp;#39;Discount amount&amp;#39;, `full_amount` decimal(8,2) NOT NULL COMMENT &amp;#39;Minimum purchase amount&amp;#39;, `score` int(10) unsigned NOT NULL DEFAULT &amp;#39;0&amp;#39; COMMENT &amp;#39;Redemption points required&amp;#39;, `start_date` date NOT NULL COMMENT &amp;#39;Start date&amp;#39;, `end_date` date NOT NULL COMMENT &amp;#39;Expiry date&amp;#39;, `created_at` timestamp NULL DEFAULT NULL COMMENT &amp;#39;Creation time&amp;#39;, `updated_at` timestamp NULL DEFAULT NULL COMMENT &amp;#39;Update time&amp;#39;, # User Coupon Table `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(10) unsigned COMMENT &amp;#39;User ID&amp;#39;, `title` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT &amp;#39;Coupon title&amp;#39;, `amount` decimal(8,2) NOT NULL COMMENT &amp;#39;Discount amount&amp;#39;, `full_amount` decimal(8,2) NOT NULL COMMENT &amp;#39;Minimum purchase amount&amp;#39;, `start_date` date NOT NULL COMMENT &amp;#39;Start date&amp;#39;, `end_date` date NOT NULL COMMENT &amp;#39;Expiry date&amp;#39;, `used_at` timestamp NULL DEFAULT NULL COMMENT &amp;#39;Usage time&amp;#39;, `created_at` timestamp NULL DEFAULT NULL COMMENT &amp;#39;Creation time&amp;#39;, `updated_at` timestamp NULL DEFAULT NULL COMMENT &amp;#39;Update time&amp;#39;, Key workflow:</description></item><item><title>[monday-shop] Issues and Solutions Encountered During Dependency Updates</title><link>https://www.shiguopeng.cn/en/posts/2019082411/</link><pubDate>Sat, 24 Aug 2019 11:17:03 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2019082411/</guid><description>This weekend, I updated the monday-shop system.
The most significant challenges came from upgrading laravel-admin to the latest version. This backend framework is particularly valuable as it allows developers to focus on core backend logic. First Issue: Composer Dependency Errors
Initial composer install failed due to locked mirror sources. Solved by switching to Alibaba Cloud Composer Mirror.
Laravel-admin Upgrade Challenges
monday-shop Key functionality affected:
Soft Delete (下架) Restore (上架) Version-Specific Problems:</description></item><item><title>Speed Up Your Framework: How to Reduce Service Provider Boot Time</title><link>https://www.shiguopeng.cn/en/posts/2019032219/</link><pubDate>Fri, 22 Mar 2019 19:32:57 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2019032219/</guid><description>Laravel has a powerful feature called service providers that makes it easy to access various services. However, this convenience comes at the cost of framework bloat. Here&amp;rsquo;s how to optimize unnecessary service providers.
Step 1: Identify Unnecessary Service Providers Run php artisan package:discover or composer dump-auto to see all auto-loaded service providers:
Service Providers Step 2: Conditionally Load Providers Example 1: Admin Panel Optimization The encore/laravel-admin package (a backend panel) boots on every request.</description></item><item><title>Dijkstra Algorithm</title><link>https://www.shiguopeng.cn/en/posts/2019031312/</link><pubDate>Wed, 13 Mar 2019 12:52:43 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2019031312/</guid><description>Suppose we have the following graph:
// 3 // e+-----------------+ // ^ | // 2| | // | | // 1 + 1 3 | // a +------&amp;gt; b +---&amp;gt; d +---+ | // + + | | // | | v | // 2 | |4 g &amp;lt;--+ // | | ^ // v v 1 | // c f +---+ // + ^ // | | // | 2 | // +------------------+ To find the shortest path from node a to node g, we can use the Dijkstra algorithm.</description></item><item><title>DFS (Depth-First Search) and BFS (Breadth-First Search)</title><link>https://www.shiguopeng.cn/en/posts/2019030617/</link><pubDate>Wed, 06 Mar 2019 17:05:49 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2019030617/</guid><description>BFS stands for Breadth-First-Search
DFS stands for Depth-first search
A classic LeetCode problem &amp;ldquo;Number of Islands&amp;rdquo;:
Given a 2D grid map of 1s (land) and 0s (water), count the number of islands. An island is surrounded by water and formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are surrounded by water.
Input:
11000
11000
00100
00011
Output: 3
Although this problem is categorized under BFS, implementing it with DFS may be more intuitive.</description></item><item><title>Reverse Linked List - Recursive Approach</title><link>https://www.shiguopeng.cn/en/posts/2019021815/</link><pubDate>Mon, 18 Feb 2019 15:43:12 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2019021815/</guid><description>Recently encountered a linked list reversal problem on LeetCode:
Reverse a singly linked list. Example: Input: 1-&amp;gt;2-&amp;gt;3-&amp;gt;4-&amp;gt;5-&amp;gt;NULL Output: 5-&amp;gt;4-&amp;gt;3-&amp;gt;2-&amp;gt;1-&amp;gt;NULL Iterative Solution /** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* reverseList(struct ListNode* head) { struct ListNode *tmpHead = head, *nextNode; if (NULL == head) { return head; } while (NULL != head-&amp;gt;next) { // Move the next node of current &amp;#39;head&amp;#39; to real head position nextNode = head-&amp;gt;next; head-&amp;gt;next = head-&amp;gt;next-&amp;gt;next; nextNode-&amp;gt;next = tmpHead; tmpHead = nextNode; } return tmpHead; } Recursive Solution /** * Definition for singly-linked list.</description></item><item><title>Stress Testing with JMeter</title><link>https://www.shiguopeng.cn/en/posts/2018120411/</link><pubDate>Tue, 04 Dec 2018 11:56:11 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2018120411/</guid><description>I previously used ab (ApacheBench), the built-in stress testing tool from Apache, but found it less convenient. After some research, I discovered a tool called JMeter.
Installing JDK Since JMeter is developed in Java, we need a Java Runtime Environment (JRE). For simplicity, we&amp;rsquo;ll install the full JDK (Java Development Kit):
Visit the official Oracle download page:
https://www.oracle.com/technetwork/java/javase/downloads/index.html Select JDK download:
JDK Download Accept the license agreement and download the appropriate version for your OS (Windows in this case):</description></item><item><title>Converting UTC Time to Local Time</title><link>https://www.shiguopeng.cn/en/posts/2018111517/</link><pubDate>Thu, 15 Nov 2018 17:15:54 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2018111517/</guid><description>When working with UTC time formats that need conversion to local time (e.g., UTC+8), here&amp;rsquo;s a breakdown of the process for the input format yyyy-MM-ddTHH:mm:ss.SSSZ:
yyyy: 4-digit year MM: 2-digit month (01-12) dd: 2-digit day (01-31) T: Date/time separator HH: 24-hour format hour (00-23) mm: Minutes (00-59) ss: Seconds (00-59) SSS: Milliseconds (3 digits) Z: Timezone offset (e.g., +0100 for UTC+1) Example Conversion:
Input: 2018-01-01T12:00:00.000+0100 (UTC+1)
Local Output (UTC+8): 2018-01-01 19:00:00.</description></item><item><title>In Route Permission Control, a Paginated List Permission Can Simultaneously Control All List Permissions</title><link>https://www.shiguopeng.cn/en/posts/2018101716/</link><pubDate>Wed, 17 Oct 2018 16:12:05 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2018101716/</guid><description>Recently encountered an issue while implementing permission control for API endpoints.
This builds upon our previous permission control method: Using Route-Based Permission Control in Laravel (Applicable Beyond Laravel, as a Conceptual Approach)
We have two route aliases:
Paginated city list: cities.index
Complete city list: cities.index.all
These represent two separate permissions. To ensure users with only the cities.index permission can also access cities.index.all (since both belong to list operations under normal logic), we need to make minor adjustments to our validation logic.</description></item><item><title>Elegantly Validate Date Must Be Greater Than Today in Laravel</title><link>https://www.shiguopeng.cn/en/posts/2018091911/</link><pubDate>Wed, 19 Sep 2018 11:51:03 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2018091911/</guid><description>We often encounter scenarios like ticket purchasing queries that require date range validation: the start date must be greater than or equal to today, and the end date must be greater than or equal to the start date. Version Laravel 5.5.40 PHP 7.1 Implementation Steps Create a Form Request:
Laravel Note: Remember to return true in the authorize() method since we&amp;rsquo;re handling authentication elsewhere
Basic validation rules:
Laravel Special validation challenge:</description></item><item><title>The Concise Yet Powerful Macroable Macros in Laravel</title><link>https://www.shiguopeng.cn/en/posts/2018071012/</link><pubDate>Tue, 10 Jul 2018 12:46:43 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2018071012/</guid><description>From Baidu Encyclopedia:
A macro in computer science refers to batch processing rules. Generally, it&amp;rsquo;s a pattern or syntactic substitution that defines how specific inputs (usually strings) are transformed into corresponding outputs (also strings) according to predefined rules. This substitution occurs during preprocessing, called macro expansion.
My first encounter with macros was during a university computer basics course when the professor demonstrated Office macros. Though I didn&amp;rsquo;t fully grasp it then, I remembered macros as powerful tools that could simplify repetitive tasks.</description></item><item><title>A Pitfall When Developing Optional Token-Passing API Interfaces</title><link>https://www.shiguopeng.cn/en/posts/2018062412/</link><pubDate>Sun, 24 Jun 2018 12:04:42 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2018062412/</guid><description>When developing APIs, authentication is inevitable. I use jwt-auth for this purpose. A common issue in authentication is token expiration. In the default settings of config/jwt.php, the expiration time is one hour. For better security, I&amp;rsquo;ve set it to 5 minutes. Forcing users to re-login every 5 minutes would lead to terrible user experience. This is where token refresh functionality becomes essential. Normally, we create a dedicated token refresh endpoint.</description></item><item><title>Laravel Form size Validation for Numbers</title><link>https://www.shiguopeng.cn/en/posts/2018060110/</link><pubDate>Fri, 01 Jun 2018 10:15:17 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2018060110/</guid><description>To validate a numeric exact value, I referred to the form validation documentation:
size:value
The field under validation must have a size matching the given value. For string data, value corresponds to the number of characters. For numeric data, value corresponds to the integer value. For arrays, size corresponds to the count of the array. For files, size corresponds to the file size in kilobytes.
Original validation rule:
$data = [&amp;#39;age&amp;#39; =&amp;gt; 9]; $validator = \Illuminate\Support\Facades\Validator::make($data, [&amp;#39;age&amp;#39; =&amp;gt; &amp;#39;required|size:9&amp;#39;]); if ($validator-&amp;gt;fails()) { dd($validator-&amp;gt;errors()-&amp;gt;first()); } dd(&amp;#39;pass&amp;#39;); I expected it to validate numbers directly when the input 9 is an integer.</description></item><item><title>How I Contributed to Laravel's Source Code for the First Time</title><link>https://www.shiguopeng.cn/en/posts/2018051416/</link><pubDate>Mon, 14 May 2018 16:17:35 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2018051416/</guid><description>Origin Solutions always outnumber problems, making problem discovery more valuable than problem-solving itself. The story began when debugging model events - I randomly inserted a string ID (non-standard UUID) into the database and found the model couldn&amp;rsquo;t be retrieved by this ID in my model events. When encountering issues, it&amp;rsquo;s worth checking Laravel&amp;rsquo;s issue tracker to find solvable problems. Progress After verifying my code wasn&amp;rsquo;t faulty through step-by-step debugging
Controller Event Log Discovered the ID returned by belongsToMany::sync method was incorrect</description></item><item><title>Implementation of Linked List in PHP</title><link>https://www.shiguopeng.cn/en/posts/2018042410/</link><pubDate>Tue, 24 Apr 2018 10:08:57 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2018042410/</guid><description>Starting to learn data structures
Today I changed the code font I use. Previously I used console which looked good, but today I found a more preferable style Source Code Pro.
Here are two screenshots - it&amp;rsquo;s quite pleasing!
Source Code Pro Source Code Pro Now let&amp;rsquo;s get to the main topic: linked list operations
Node Class First we need a Node class to store data &amp;lt;?php namespace LinkedList; class Node { /** * @var $data integer */ public $data; /** * Pointer to next node * * @var $next Node */ public $next; public function __construct(int $data = null) { // Initialize data assignment, can also be assigned via $node-&amp;gt;data = X; $this-&amp;gt;data = $data; } } Linked List Manager Class (For node operations) We&amp;rsquo;ll break down the manager class code into sections due to its length Head Insertion As the name suggests, insert at the head If list is empty, initialize with current node If not empty, make new node the head public function insertHead(int $data) : bool { $newNode = new Node($data); $newNode-&amp;gt;next = $this-&amp;gt;head; $this-&amp;gt;head = $newNode; return true; } Insert at Position (index=0 is head, returns false for invalid positions) public function insert(int $index = 0, int $data) : bool { if (is_null($this-&amp;gt;head) || $index === 0) { return $this-&amp;gt;insertHead($data); } $currNode = $this-&amp;gt;head; $startIndex = 1; for ($currIndex = $startIndex; !</description></item><item><title>RESTful Routing URL Naming Conventions</title><link>https://www.shiguopeng.cn/en/posts/2018040521/</link><pubDate>Thu, 05 Apr 2018 21:11:41 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2018040521/</guid><description>A previous blog briefly introduced Using RESTful in Laravel This article explains various RESTful-style route writing conventions. While not necessarily authoritative, these patterns are semantically meaningful in practice. Base Routing Typically grouped with a common prefix: Always follows API + version format /api/v1 Basic Parameters Pagination parameters using QueryString: limit page Example: /url?limit=10&amp;amp;page=1 Multi-parameter sorting: Example: /url?desc=created_at,id&amp;amp;asc=grade,updated_at Fundamental Routes List categories: method: GET /categories Create category: method: POST /categories Delete category: method: DELETE /categories/{category} Get single category: method: GET /categories/{category} Update category: method: PUT /categories/{category} Intermediate Routes Get articles under category: method: GET /categories/{category}/articles Get articles with tag: method: GET /tags/{tag}/articles Batch delete articles (avoid when possible): method: DELETE /articles/batch?</description></item><item><title>MySQL Reverse Fuzzy Lookup</title><link>https://www.shiguopeng.cn/en/posts/2018040121/</link><pubDate>Sun, 01 Apr 2018 21:56:48 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2018040121/</guid><description>When developing a WeChat auto-reply demo, I encountered this scenario:
Receive specific messages Reply with predefined content based on keywords stored in database Requires partial matching with fuzzy database queries For conventional fuzzy matching, everyone knows to use LIKE. Given this table structure:
id keyword reply 1 David This is David 2 KingDavid This is David If the input keyword is &amp;ldquo;David&amp;rdquo;, we need to find all records containing David. The SQL would be:</description></item><item><title>Quickly Set Up an LNMP Environment</title><link>https://www.shiguopeng.cn/en/posts/2018033111/</link><pubDate>Sat, 31 Mar 2018 11:55:27 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2018033111/</guid><description>Environment Specifications Linux version: CentOS7 Nginx: Default version MySQL: MariaDB PHP: Version PHP71 Linux Open required ports after server setup: 80 for HTTP 443 for HTTPS (optional) 3306 for remote MySQL connections Nginx Install Nginx on CentOS: yum install nginx -y Start Nginx: nginx Enable auto-start: systemctl enable nginx Configuration: Default config file: /etc/nginx/nginx.conf Add include /etc/nginx/conf.d/*.conf; to load custom configurations Remove default server block and create new config: vi /etc/nginx/conf.</description></item><item><title>Permission Control via Routing in Laravel (Not Limited to Laravel, Just a Conceptual Approach)</title><link>https://www.shiguopeng.cn/en/posts/2018032712/</link><pubDate>Tue, 27 Mar 2018 12:53:51 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2018032712/</guid><description>Start Permission design is a crucial feature for backend management systems. PHP already has many mature packages for this purpose, so we don&amp;rsquo;t need to reinvent the wheel (though you certainly can if preferred).
PS Here are two common historical approaches for permission verification:
Verify required permissions individually on each page Centralized verification via middleware First, let&amp;rsquo;s examine a simplified database schema (retaining only critical fields) with its ER diagram: Database Model Diagram (Note: In this design, users don&amp;rsquo;t directly possess permissions but inherit them through roles.</description></item><item><title>Building a Blog for Free with CODING [Supports Dynamic Programs]</title><link>https://www.shiguopeng.cn/en/posts/2018032617/</link><pubDate>Mon, 26 Mar 2018 17:33:16 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2018032617/</guid><description>When I first started learning, I used WordPress for blogging. Later I experimented with GitHub, tried the sophisticated GitHub Pages blog platform for quite some time, but found pure static blogs couldn&amp;rsquo;t fully meet my needs. Though various plugins could compensate, it remained a workaround.
Eventually I returned to WordPress.
Creating a CODING Repository Visit the official website (register if needed) Create a new repository
Repository Fill in repository info and click Create</description></item><item><title>Application of Laravel Model Events</title><link>https://www.shiguopeng.cn/en/posts/2018031821/</link><pubDate>Sun, 18 Mar 2018 21:02:55 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2018031821/</guid><description>In daily processing of user operation events, we sometimes need to record them for future reference or big data statistics.
Laravel handles model events conveniently: https://laravel-china.org/docs/laravel/5.5/eloquent#events
There are two approaches to Laravel model events:
Set the dispatchesEvents property to map event classes Use observers to register events (this article focuses on the second approach) Implementation Steps Create Model
php artisan make:model Log &amp;lt;?php namespace App; use Illuminate\Database\Eloquent\Model; class Log extends Model { protected $fillable = [&amp;#39;user_name&amp;#39;, &amp;#39;user_id&amp;#39;, &amp;#39;url&amp;#39;, &amp;#39;event&amp;#39;, &amp;#39;method&amp;#39;, &amp;#39;table&amp;#39;, &amp;#39;description&amp;#39;]; } Create Migration Table</description></item><item><title>The Story of Fourteen</title><link>https://www.shiguopeng.cn/en/posts/2018030522/</link><pubDate>Mon, 05 Mar 2018 22:47:04 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2018030522/</guid><description>This dream is a much older story that I felt compelled to write down due to its profound significance.
It began in a mortal village, a world of bustling markets and earthly concerns.
While walking through the marketplace, celestial beings descended from the heavens - my first revelation that gods truly existed. When they announced the Heavenly Court needed recruits, I learned mortals could ascend to immortality.
I still don&amp;rsquo;t know why I was chosen.</description></item><item><title>The Secret of the Pyramids</title><link>https://www.shiguopeng.cn/en/posts/2018030221/</link><pubDate>Fri, 02 Mar 2018 21:18:09 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2018030221/</guid><description>I’m writing this down because of an unusual dream I had long ago. Tonight, while flipping through my notebook, I recalled this extraordinary vision.
In the dream, I was a slave laboring alongside others to build a pyramid. It seemed impossible that mere humans could construct such a marvel without assistance—in reality, people might speculate about alien intervention.
But in the dream, there were only shackled workers (perhaps prisoners would be a better term).</description></item><item><title>Insights on Developing RESTful APIs with Laravel</title><link>https://www.shiguopeng.cn/en/posts/2018030122/</link><pubDate>Thu, 01 Mar 2018 22:06:16 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2018030122/</guid><description>Here are some insights I’ve gained while working with Laravel to develop RESTful APIs.
Getting Started API Authentication: For public APIs, consider OAuth2.0; for private/internal APIs, token-based authentication (e.g., JWT) is often sufficient. Versioning: Include an API version in routes for future scalability: Route::prefix(&amp;#39;v1&amp;#39;)-&amp;gt;group(function () { // Routes here }); CORS Handling: Use the barryvdh/laravel-cors package for seamless cross-origin requests. Sample API Endpoint
Example Code Authentication Use jwt-auth for JWT-based authentication.</description></item><item><title>One-Click PHP Extension Installer</title><link>https://www.shiguopeng.cn/en/posts/2018022717/</link><pubDate>Tue, 27 Feb 2018 17:00:02 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2018022717/</guid><description>When beginners learn PHP through tutorial videos, they often encounter the need to enable extensions like openssl and curl, which can be activated by simply modifying the php.ini file. However, installing extensions like redis and memcache requires finding the correct versions matching their PHP, NTS, VC, and Windows environment - a process that&amp;rsquo;s straightforward for experienced developers but challenging for newcomers.
To solve this problem, we&amp;rsquo;ve developed a one-click PHP extension installer program.</description></item><item><title>imagejpg-imagepng-imagegif Can Generate Images but Fail to Output to Browser</title><link>https://www.shiguopeng.cn/en/posts/2018022716/</link><pubDate>Tue, 27 Feb 2018 16:55:26 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2018022716/</guid><description>If your imagejpg, imagepng, or imagegif functions can generate images but fail to display them in the browser, this article will help you resolve the issue.
Initially, I compared a working file with the problematic one and found no visible differences - not even a single character.
Undeterred, I downloaded a text comparison tool. The truth gradually emerged:
Text comparison tool As shown, the left (working) file uses standard UTF-8, while the right (problematic) file uses UTF-8 + BOM.</description></item><item><title>Hello, World!</title><link>https://www.shiguopeng.cn/en/posts/2018022714/</link><pubDate>Tue, 27 Feb 2018 14:46:56 +0800</pubDate><guid>https://www.shiguopeng.cn/en/posts/2018022714/</guid><description>hello, world readme
Key modifications made:
Kept English title unchanged Translated description to English Translated Chinese tags: 搭建 → setup, 博客 → blog Maintained technical terms: hugo/wordress/hexo/Github Adjusted timezone format to +08:00 Preserved code blocks and markdown syntax Maintained mixed-case spelling for &amp;ldquo;Github&amp;rdquo; (though technically should be &amp;ldquo;GitHub&amp;rdquo;) as per original</description></item></channel></rss>