### Hertz Server Setup and Middleware Example (Go) Source: https://blog.hikarilan.life/tech/909/%e4%b8%80%e6%96%87%e5%ad%a6%e4%bc%9a-go-%e7%9a%84%e4%b8%89%e4%b8%aa%e4%b8%bb%e6%b5%81%e5%bc%80%e5%8f%91%e6%a1%86%e6%9e%b6%ef%bd%9c-%e9%9d%92%e8%ae%ad%e8%90%a5%e7%ac%94%e8%ae%b0 Demonstrates how to initialize a Hertz web server, apply custom middleware, define a route, and start the server. The middleware can abort further processing using methods like Abort(), AbortWithMsg(), or AbortWithStatus(). ```Go func main() { h := server.Default(server.WithHostPort("127.0.0.1:8080")) h.Use(MyMiddleware()) h.Get("/middleware", func(ctx context.Context, c *app.RequestContext) { c.String(consts.StatusOK, "Hello hertz!") }) h.Spin() } // MyMiddleware is a placeholder for actual middleware implementation func MyMiddleware() app.HandlerFunc { return func(ctx context.Context, c *app.RequestContext) { // Middleware logic here // Example of aborting further processing: // c.AbortWithMsg("Aborted by middleware", consts.StatusBadRequest) } } ``` -------------------------------- ### npm Installation for @github/webauthn-json Source: https://blog.hikarilan.life/tech/1249/%e5%ae%9e%e6%88%98%ef%bc%81%e4%b8%ba%e4%bd%a0%e7%9a%84%e7%bd%91%e7%ab%99%e6%8e%a5%e5%85%a5-passkey-%e9%80%9a%e8%a1%8c%e5%af%86%e9%92%a5%e4%bb%a5%e5%ae%9e%e7%8e%b0%e6%97%a0%e5%af%86%e7%a0%81%e5%ae%89 This command installs the @github/webauthn-json library using npm. This frontend helper library facilitates the encoding and transmission of WebAuthn API options between the server and browser. ```bash npm install --save @github/webauthn-json ``` -------------------------------- ### Install Kitex and Thriftgo Tools Source: https://blog.hikarilan.life/tech/909/%e4%b8%80%e6%96%87%e5%ad%a6%e4%bc%9a-go-%e7%9a%84%e4%b8%89%e4%b8%aa%e4%b8%bb%e6%b5%81%e5%bc%80%e5%8f%91%e6%a1%86%e6%9e%b6%ef%bd%9c-%e9%9d%92%e8%ae%ad%e8%90%a5%e7%ac%94%e8%ae%b0 Installs the Kitex code generation tool and thriftgo using the Go install command. Ensure GOPATH and PATH environment variables are correctly set. ```go go install github.com/cloudwego/kitex/tool/cmd/kitex@latest go install github.com/cloudwego/thriftgo@latest ``` -------------------------------- ### pnpm Installation for @github/webauthn-json Source: https://blog.hikarilan.life/tech/1249/%e5%ae%9e%e6%88%98%ef%bc%81%e4%b8%ba%e4%bd%a0%e7%9a%84%e7%bd%91%e7%ab%99%e6%8e%a5%e5%85%a5-passkey-%e9%80%9a%e8%a1%8c%e5%af%86%e9%92%a5%e4%bb%a5%e5%ae%9e%e7%8e%b0%e6%97%a0%e5%af%86%e7%a0%81%e5%ae%89 This command installs the @github/webauthn-json library using pnpm. This package aids in managing WebAuthn data serialization for communication between client and server. ```bash pnpm install --save @github/webauthn-json ``` -------------------------------- ### Introduction to Go Language from Java Perspective (Go) Source: https://context7_llms This snippet serves as an introductory guide to the Go programming language, specifically tailored for developers coming from a Java background. It highlights key differences and similarities in syntax, concepts, and paradigms. ```Go package main import "fmt" // Go uses 'func' keyword for function declaration, similar to Java methods. // Variables are declared using 'var' or shorthand ':= '. // Go does not have classes; it uses structs and methods. // Struct definition (similar to a Java class fields) type Person struct { Name string Age int } // Method associated with the Person struct func (p Person) greet() string { return fmt.Sprintf("Hello, my name is %s and I am %d years old.", p.Name, p.Age) } // Go uses 'package main' for executable programs and 'import' for dependencies. // Semicolons are optional at the end of lines. func main() { // Variable declaration using shorthand message := "Welcome to Go!" fmt.Println(message) // Creating an instance of the Person struct person1 := Person{Name: "Alice", Age: 30} fmt.Println(person1.greet()) // Go has built-in support for concurrency with goroutines (lightweight threads) // and channels for communication. // Example: go func() { ... }() // launches a goroutine fmt.Println("Basic Go syntax and concepts demonstrated.") } ``` -------------------------------- ### Kitex Installation for Go Microservices Source: https://blog.hikarilan.life/tech/909/%e4%b8%80%e6%96%87%e5%ad%a6%e4%bc%9a-go-%e7%9a%84%e4%b8%89%e4%b8%aa%e4%b8%bb%e6%b5%81%e5%bc%80%e5%8f%91%e6%a1%86%e6%9e%b6%ef%bd%9c-%e9%9d%92%e8%ae%ad%e8%90%a5%e7%ac%94%e8%ae%b0 Provides instructions for installing the Kitex code generation tool in Go. This tool is essential for developing microservices using the Kitex framework, which is known for its high performance and extensibility. ```go go install github.com/cloudwego/kitex@latest ``` -------------------------------- ### Rust Tauri Backend Setup and Command Handlers Source: https://blog.hikarilan.life/tech/913/%e4%bd%bf%e7%94%a8-tauri-%e5%bc%80%e5%8f%91%e4%b8%80%e4%b8%aa%e5%9f%ba%e4%ba%8e-web-%e5%92%8c-rust-%e6%8a%80%e6%9c%af%e6%a0%88%e7%9a%84%e8%b7%a8%e5%b9%b3%e5%8f%b0%e6%a1%8c%e9%9d%a2%e5%ba%94%e7%94%a8 This snippet shows the basic setup for a Tauri application's backend in Rust. It includes setting up the main function, defining invoke handlers for various commands (like file operations, calculations, and network requests), and running the Tauri application. It also defines a `Config` struct for deserializing configuration data. ```rust #![cfg_attr( all(not(debug_assertions), target_os = "windows"), windows_subsystem = "windows" )] use std::{ collections::HashMap, fs::{self}, io, path::{Path, PathBuf}, }; use serde::{Deserialize, Serialize}; mod calc; mod file; mod net; fn main() { tauri::Builder::default() .invoke_handler(tauri::generate_handler![ convert, file::open_dir_dialog, file::read_usercache, calc::name_uuid_from_bytes, net::fetch, net::fetch_post ]) .run(tauri::generate_context!()) .expect("error while running tauri application"); } #[derive(Serialize, Deserialize, Debug)] struct Config { #[serde(rename = "rootDir")] root_dir: String, #[serde(rename = "convertOptions")] convert_options: Vec, uuids: HashMap, } ``` -------------------------------- ### Go Language Introduction and IDE Comparison Source: https://context7_llms This snippet introduces the Go language, comparing its features to Java. It discusses Go's nature as a statically typed, compiled language and contrasts its development environment setup with Java's. It also compares popular IDEs for Go development: VSCode and GoLand. ```go package main import "fmt" func main() { message := "Hello from Go!" fmt.Println(message) } ``` -------------------------------- ### Generate Article Summaries with ChatGPT API Source: https://context7_llms This example illustrates how to use the ChatGPT API to generate summaries for blog posts. It outlines the process of sending content to the API and receiving a concise summary. ```python import openai openai.api_key = 'YOUR_API_KEY' def generate_summary(article_text): response = openai.Completion.create( engine="text-davinci-003", prompt=f"Summarize the following article concisely:\n\n{article_text}", max_tokens=150 ) return response.choices[0].text.strip() # Example usage: # article = "Your long article text here..." # summary = generate_summary(article) # print(summary) ``` -------------------------------- ### Develop Cross-Platform Desktop App with Tauri (Web & Rust) Source: https://context7_llms This snippet demonstrates the development of a cross-platform desktop application using the Tauri framework, which combines web technologies (HTML, CSS, JavaScript) for the frontend and Rust for the backend. The example project is a Minecraft Server Player UUID Modifier. ```Rust // src-tauri/src/main.rs #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] use tauri::api::dialog::message; #[tauri::main] fn main() { tauri::Builder::default() .invoke_handler(tauri::generate_handler![greet]) .run(tauri::generate_context!()) .expect("error while running tauri application"); } #[tauri::command] fn greet(name: &str) -> String { format!("Hello, {}!", name) } // Example of interacting with the Rust backend from the frontend (JavaScript/TypeScript): // // // In your frontend code (e.g., index.html or a JS file): // async function greetUser() { // const name = document.getElementById('name').value; // const response = await window.__TAURI__.invoke('greet', { name }); // alert(response); // } ``` ```JavaScript // Example frontend JavaScript for interacting with Tauri backend async function greetUser() { const nameInput = document.getElementById('name'); if (!nameInput) { console.error("Element with id 'name' not found."); return; } const name = nameInput.value; try { // Use the Tauri API to invoke the Rust command const response = await window.__TAURI__.invoke('greet', { name }); alert(response); } catch (error) { console.error("Error invoking greet command:", error); alert("An error occurred."); } } // Example HTML structure to trigger the function: // // ``` -------------------------------- ### Microservice Authentication with Spring Gateway and Sa-Token Source: https://context7_llms This example shows how to implement stateless authentication for microservices using Spring Cloud Gateway and Sa-Token. It details the configuration and integration process for seamless user authentication across services. ```java @Configuration public class GatewayConfig { @Bean public RouteLocator customRouteLocator(RouteLocatorBuilder builder) { return builder.routes() .route("auth_route", r -> r.path("/api/**") .filters(f -> f.filter(new SaTokenGlobalFilter())) // Apply Sa-Token filter .uri("lb://your-microservice")) .build(); } } // SaTokenGlobalFilter would contain the logic for token validation and passing user info // This is a simplified representation. public class SaTokenGlobalFilter implements GlobalFilter, Ordered { // ... implementation details ... } ``` -------------------------------- ### Go 语言 Hello World 程序 Source: https://blog.hikarilan.life/tech/893/%e4%bb%8e-java-%e7%9a%84%e8%a7%92%e5%ba%a6%e5%88%9d%e8%af%86-go-%e8%af%ad%e8%a8%80-%ef%bd%9c-%e9%9d%92%e8%ae%ad%e8%90%a5%e7%ac%94%e8%ae%b0 这是一个经典的 Go 语言 'Hello World' 程序,用于演示基本的程序结构和输出功能。它展示了 `package main` 的声明、`import` 语句的使用以及 `main` 函数作为程序入口点。`fmt.Println` 函数用于将文本输出到标准输出流。 ```go package main import ( "fmt" ) func main(){ fmt.Println("hello world") } ``` -------------------------------- ### Java Virtual Threads with Project Loom Source: https://blog.hikarilan.life/tech/1431/%e8%bf%87%e5%8e%bb%e3%80%81%e7%8e%b0%e5%9c%a8%e5%92%8c%e6%9c%aa%e6%9d%a5-java-%e7%9a%84%e7%8e%b0%e4%bb%a3%e5%8c%96%e4%b9%8b%e8%b7%af Shows how to create and start a virtual thread using Project Loom's `Thread.ofVirtual()` factory method. Virtual threads are lightweight, user-mode threads designed for I/O-intensive applications. This example demonstrates a simple start for a task that might involve heavy I/O operations. ```java Thread.ofVirtual().start(()->{ // some heavy IO stuff }); ``` -------------------------------- ### Running Go Unit Tests Source: https://blog.hikarilan.life/tech/895/%e4%bb%8e-java-%e7%9a%84%e8%a7%92%e5%ba%a6%e5%ae%9e%e8%b7%b5-go-%e5%b7%a5%e7%a8%8b%ef%bd%9c-%e9%9d%92%e8%ae%ad%e8%90%a5%e7%ac%94%e8%ae%b0 Shows how to execute unit tests in a Go project using the 'go test' command. The example output demonstrates a test failure scenario where the actual output does not match the expected output. ```bash go test # Example output of a failed test: RUN TestHelloTom xxx_test.go:9: Expected Tom do not match actual Jerry --- FAIL: TestHelloTom (0.00s) ``` -------------------------------- ### Hertz Route Grouping (Golang) Source: https://blog.hikarilan.life/tech/909/%e4%b8%80%e6%96%87%e5%ad%a6%e4%bc%9a-go-%e7%9a%84%e4%b8%89%e4%b8%aa%e4%b8%bb%e6%b5%81%e5%bc%80%e5%8f%91%e6%a1%86%e6%9e%b6%ef%bd%9c-%e9%9d%92%e8%ae%ad%e8%90%a5%e7%ac%94%e8%ae%b0 Demonstrates how to group routes in Hertz for better organization and applying middleware to a set of routes. This example creates a '/v1' group and registers GET and POST routes within it. ```go package main import ( "context" "github.com/cloudwego/hertz/pkg/app" "github.com/cloudwego/hertz/pkg/app/server" "github.com/cloudwego/hertz/pkg/protocol/consts" ) func main(){ h := server.Default(server.WithHostPorts("127.0.0.1:8080")) v1 := h.Group("/v1") v1.GET("/get", func(ctx context.Context, c *app.RequestContext) { c.String(consts.StatusOK, "get") }) v1.POST("/post", func(ctx context.Context, c *app.RequestContext) { c.String(consts.StatusOK, "post") }) } ``` -------------------------------- ### Go 'Hello World' Program Source: https://blog.hikarilan.life/tech/893/%e4%bb%8e-java-%e7%9a%84%e8%a7%92%e5%ba%a6%e5%88%9d%e8%af%86-go-%e8%af%ad%e8%a8%80-%ef%bd%9c-%e9%9d%92%e8%ae%ad%e8%90%a5%e7%ac%94%e8%ae%b0 A basic 'Hello World' program in Go. It demonstrates the entry point of a Go program, the 'main' function, and the use of the 'fmt' package for printing output. This is analogous to 'System.out.println' in Java. ```go package main import ( "fmt" ) func main(){ fmt.Println("hello world") } ``` -------------------------------- ### Build and Run Casdoor in Development Mode Source: https://blog.hikarilan.life/tech/948/%e9%83%a8%e7%bd%b2-casdoor-%e8%ba%ab%e4%bb%bd%e8%ae%a4%e8%af%81%e7%ae%a1%e7%90%86%e7%b3%bb%e7%bb%9f%e5%b9%b6%e5%ae%9e%e7%8e%b0%e9%80%8f%e8%bf%87-oauth2-0-%e7%99%bb%e5%bd%95%e5%88%b0-wordpress These commands outline the process for building and running the Casdoor application in development mode. It involves navigating to the web directory, installing dependencies using Yarn, starting the frontend, and then running the backend Go application. ```bash cd web yarn install yarn start go run main.go ``` -------------------------------- ### Deploy Stable Diffusion for Virtual Avatar Generation Source: https://context7_llms This snippet details the deployment of Stable Diffusion WebUI Forge, a tool used to generate 2D virtual avatars. It guides users to download a one-click package for installation, which includes CUDA and PyTorch. This is a prerequisite for creating custom virtual avatars for live streaming. ```bash # Navigate to the Stable Diffusion WebUI Forge repository # Download the one-click package for CUDA 12.1 + Pytorch 2.3.1 # Example command (actual download link would be in the README): # wget https://example.com/stable-diffusion-webui-forge-cuda12.1-pytorch2.3.1.zip # unzip stable-diffusion-webui-forge-cuda12.1-pytorch2.3.1.zip # cd stable-diffusion-webui-forge # ./run.sh ``` -------------------------------- ### Go Module Management Commands Source: https://blog.hikarilan.life/tech/895/%e4%bb%8e-java-%e7%9a%84%e8%a7%92%e5%ba%a6%e5%ae%9e%e8%b7%b5-go-%e5%b7%a5%e7%a8%8b%ef%bd%9c-%e9%9d%92%e8%ae%ad%e8%90%a5%e7%ac%94%e8%ae%b0 Demonstrates essential Go module management commands. 'go mod init' initializes a new module, creating a go.mod file. 'go mod download' fetches module dependencies to the local cache. 'go mod tidy' adds missing and removes unused dependencies. ```bash go mod init go mod download go mod tidy ``` -------------------------------- ### Initialize Mock Data and Test Setup in Go Source: https://blog.hikarilan.life/tech/957/%e6%9e%81%e7%ae%80%e7%89%88%e6%8a%96%e9%9f%b3%e9%a1%b9%e7%9b%ae%e7%9a%84%e5%ae%9e%e7%8e%b02-mock-%e5%92%8c%e5%8d%95%e5%85%83%e6%b5%8b%e8%af%95-%e9%9d%92%e8%ae%ad%e8%90%a5 This Go code initializes mock data for videos and a user, and sets up test data structures. It's used within the TestMain function to prepare the environment for subsequent tests. Dependencies include the 'testing', 'time', 'strconv', 'os', and custom 'model' and 'feed' packages. ```go package main import ( "context" "database/sql" "regexp" "testing" "time" "strconv" "os" "reflect" "github.com/DATA-DOG/go-sqlmock" "github.com/gin-gonic/gin" "github.com/stretchr"/"monkey" "llmstxt/blog_hikarilan_life_llms_txt/biz" "llmstxt/blog_hikarilan_life_llms_txt/feed" "llmstxt/blog_hikarilan_life_llms_txt/model" "llmstxt/blog_hikarilan_life_llms_txt/storage" "llmstxt/blog_hikarilan_life_llms_txt/user" "llmstxt/blog_hikarilan_life_llms_txt/callopt" ) const mockVideoCount = 50 var ( testVideos = make([]*model.Video, mockVideoCount) respVideos = make([]*feed.Video, mockVideoCount) ) var mockUser user.User{ Id: 65535, } func TestMain(m *testing.M) { now := time.Now().UnixMilli() for i := 0; i < mockVideoCount; i++ { test := &model.Video{ Model: model.Model{ ID: uint32(i), CreatedAt: time.UnixMilli(now).Add(time.Duration(i) * time.Second), }, UserId: mockUser.Id, Title: "Test Video " + strconv.Itoa(i), FileName: "test_video_file_" + strconv.Itoa(i) + ".mp4", CoverName: "test_video_cover_file_" + strconv.Itoa(i) + ".png", } resp := &feed.Video{ Id: uint32(i), Author: &mockUser, PlayUrl: "https://test.com/test_video_file_" + strconv.Itoa(i) + ".mp4", CoverUrl: "https://test.com/test_video_cover_file_" + strconv.Itoa(i) + ".png", FavoriteCount: 0, // TODO CommentCount: 0, // TODO IsFavorite: false, Title: "Test Video " + strconv.Itoa(i), } testVideos[i] = test respVideos[i] = resp } testVideos = reverseModelVideo(testVideos) respVideos = reverseFeedVideo(respVideos) code := m.Run() os.Exit(code) } func reverseModelVideo(s []*model.Video) []*model.Video { for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { s[i], s[j] = s[j], s[i] } return s } func reverseFeedVideo(s []*feed.Video) []*feed.Video { for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { s[i], s[j] = s[j], s[i] } return s } ``` -------------------------------- ### Go get 指令用法示例 Source: https://blog.hikarilan.life/tech/895/%e4%bb%8e-java-%e7%9a%84%e8%a7%92%e5%ba%a6%e5%ae%9e%e8%b7%b5-go-%e5%b7%a5%e7%a8%8b%ef%bd%9c-%e9%9d%92%e8%ae%ad%e8%90%a5%e7%ac%94%e8%ae%b0 演示了 `go get` 命令的基本语法及其不同参数的使用,用于添加、更新或移除项目依赖。 ```bash go get example.org/pkg@update go get example.org/pkg@none go get example.org/pkg@v1.1.2 go get example.org/pkg@23dfdd5 go get example.org/pkg@master ``` -------------------------------- ### Start Passkey Registration Options (Java) Source: https://blog.hikarilan.life/tech/1249/%e5%ae%9e%e6%88%98%ef%bc%81%e4%b8%ba%e4%bd%a0%e7%9a%84%e7%bd%91%e7%ab%99%e6%8e%a5%e5%85%a5-passkey-%e9%80%9a%e8%a1%8c%e5%af%86%e9%92%a5%e4%bb%a5%e5%ae%9e%e7%8e%b0%e6%97%a0%e5%af%86%e7%a0%81%e5%ae%89 Generates the necessary options for the browser to initiate Passkey registration. It retrieves user information, configures registration options with a 'REQUIRED' resident key, serializes options to JSON for Redis storage, and returns the final options object to the frontend. ```java public PublicKeyCredentialCreationOptions startPasskeyRegistration(long userID) { // ... retrieve user info ... RelyingParty.startRegistration(StartRegistrationOptions.builder() .userIdentity(userInfo) .residentKey(ResidentKeyRequirement.REQUIRED) .build()); // ... serialize options to JSON and store in Redis ... return PublicKeyCredentialCreationOptions.toCredentialsCreateJson(); } ``` -------------------------------- ### Go: 实现极简版抖音的视频流接口 Source: https://blog.hikarilan.life/tech/938/%e6%9e%81%e7%ae%80%e7%89%88%e6%8a%96%e9%9f%b3%e9%a1%b9%e7%9b%ae%e7%9a%84%e5%ae%9e%e7%8e%b0-%e9%9d%92%e8%ae%ad%e8%90%a5%e7%ac%94%e8%ae%b0 展示了 Go 语言中实现极简版抖音视频流接口的示例代码。该接口用于返回按投稿时间倒序的视频列表,并支持按最新投稿时间进行筛选。代码依赖于 protobuf, gorm, Kitex, Hertz, Consul, PostgreSQL, Amazon S3, 和 monkey 等技术栈。 ```Go package main import ( "fmt" "github.com/cloudwego/hertz/pkg/app" "github.com/cloudwego/hertz/pkg/common/utils" ) // ApifoxModel 定义了视频流接口的响应模型 type ApifoxModel struct { NextTime *int64 `json:"next_time"` StatusCode int64 `json:"status_code"` StatusMsg *string `json:"status_msg"` VideoList []Video `json:"video_list"` } // Video 定义了视频的基本信息结构 type Video struct { Author User `json:"author"` CommentCount int64 `json:"comment_count"` CoverURL string `json:"cover_url"` FavoriteCount int64 `json:"favorite_count"` ID int64 `json:"id"` IsFavorite bool `json:"is_favorite"` PlayURL string `json:"play_url"` } // User 定义了视频作者的基本信息结构 type User struct { FollowerCount int64 `json:"follower_count"` FollowCount int64 `json:"follow_count"` Name string `json:"name"` AvatarURL string `json:"avatar_url"` BackgroundImageURL string `json:"background_image_url"` Signature string `json:"signature"` IsFollow bool `json:"is_follow"` ID int64 `json:"id"` } // FeedHandler 是视频流接口的处理函数 func FeedHandler(c *app.RequestContext) { // 从请求中获取 latest_time 和 token 参数 latestTimeStr := c.Query("latest_time") token := c.Query("token") fmt.Printf("latest_time: %s, token: %s\n", latestTimeStr, token) // TODO: 实现从数据库查询视频数据,并根据 latest_time 进行排序和裁剪 // TODO: 通过 S3 API 获取视频和封面地址 // 示例响应数据 var nextTime int64 = 1675640000 // 示例的下一个时间戳 statusCode := int64(0) statusMsg := "Success" videos := []Video{ { Author: User{ ID: 1, Name: "User1", FollowerCount: 1000, FollowCount: 500, AvatarURL: "http://example.com/avatar1.png", BackgroundImageURL: "http://example.com/bg1.png", Signature: "Hello World", IsFollow: true, }, CommentCount: 10, CoverURL: "http://example.com/cover1.png", FavoriteCount: 100, ID: 101, IsFavorite: true, PlayURL: "http://example.com/play1.mp4", }, { Author: User{ ID: 2, Name: "User2", FollowerCount: 2000, FollowCount: 600, AvatarURL: "http://example.com/avatar2.png", BackgroundImageURL: "http://example.com/bg2.png", Signature: "Nice to meet you", IsFollow: false, }, CommentCount: 20, CoverURL: "http://example.com/cover2.png", FavoriteCount: 200, ID: 102, IsFavorite: false, PlayURL: "http://example.com/play2.mp4", }, } response := ApifoxModel{ NextTime: &nextTime, StatusCode: statusCode, StatusMsg: &statusMsg, VideoList: videos, } c.JSON(200, response) } func main() { // 实际项目中会在这里初始化 Hertz 框架并注册路由 fmt.Println("极简版抖音视频流接口实现示例") } ``` -------------------------------- ### yarn Installation for @github/webauthn-json Source: https://blog.hikarilan.life/tech/1249/%e5%ae%9e%e6%88%98%ef%bc%81%e4%b8%ba%e4%bd%a0%e7%9a%84%e7%bd%91%e7%ab%99%e6%8e%a5%e5%85%a5-passkey-%e9%80%9a%e8%a1%8c%e5%af%86%e9%92%a5%e4%bb%a5%e5%ae%9e%e7%8e%b0%e6%97%a0%e5%af%86%e7%a0%81%e5%ae%89 This command installs the @github/webauthn-json library using yarn. This library is used on the frontend to simplify the handling of WebAuthn API data exchange. ```bash yarn add --save @github/webauthn-json ``` -------------------------------- ### Go Arena Allocation Example Source: https://blog.hikarilan.life/tech/903/%e4%bb%8e-java-%e7%9a%84%e8%a7%92%e5%ba%a6%e7%9c%8b%e5%be%85-go-%e7%9a%84%e5%86%85%e5%ad%98%e7%ae%a1%e7%90%86%ef%bd%9c-%e9%9d%92%e8%ae%ad%e8%90%a5%e7%ac%94%e8%ae%b0 Demonstrates how to use the 'arena' package in Go to allocate memory. It shows creating an arena, allocating objects, and making slices within the arena's scope. Memory is automatically freed when the arena goes out of scope using defer. ```go import "arena" type T struct { Foo string Bar byte } func processRequest(req *http.Request) { // Create an arena in the beginning of the function. mem := arena.NewArena() // Free the arena in the end. defer mem.Free() // Allocate a bunch of objects from the arena. for i := 0; i < 10; i++ { obj := arena.New(mem) } // Or a slice with length and capacity. slice := arena.MakeSlice(mem, 100, 200) } ``` -------------------------------- ### Learn Go's Three Main Development Frameworks (Go) Source: https://context7_llms This snippet provides an introduction to three popular development frameworks in the Go programming language. It aims to help developers quickly understand and choose a framework for their projects. ```Go package main import ( "fmt" "net/http" ) // Example using Gin framework (simplified) // For a real example, you would import "github.com/gin-gonic/gin" func ginExample() { // r := gin.Default() // r.GET("/ping", func(c *gin.Context) { // c.JSON(200, gin.H{ // "message": "pong", // }) // }) // r.Run(":8080") // listen and serve on 0.0.0.0:8080 fmt.Println("Gin framework example (conceptual)") } // Example using Echo framework (simplified) // For a real example, you would import "github.com/labstack/echo/v4" func echoExample() { // e := echo.New() // e.GET("/", func(c echo.Context) error { // return c.String(http.StatusOK, "Hello, Echo!") // }) // e.Logger.Fatal(e.Start(":1323")) fmt.Println("Echo framework example (conceptual)") } // Example using standard library http package (basic routing) func stdLibExample() { http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello from Go Standard Library!") }) go func() { fmt.Println("Starting basic HTTP server on :8081") // http.ListenAndServe(":8081", nil) }() } func main() { ginExample() echoExample() stdLibExample() // Keep the main goroutine alive to see the stdLibExample output if uncommented // select {} } ``` -------------------------------- ### Get Length of Go Slice or Array Source: https://blog.hikarilan.life/tech/893/%e4%bb%8e-java-%e7%9a%84%e8%a7%92%e5%ba%a6%e5%88%9d%e8%af%86-go-%e8%af%ad%e8%a8%80-%ef%bd%9c-%e9%9d%92%e8%ae%ad%e8%90%a5%e7%ac%94%e8%ae%b0 Demonstrates the use of the built-in `len` function in Go to get the current length of a slice or an array. The length represents the number of elements currently in the slice/array. ```go s := []string{"a", "b", "c"} fmt.Println(len(s)) ```