### Basic Ant Web Framework Usage Example Source: https://github.com/teanft/ant/blob/main/README.md Demonstrates how to initialize an Ant HTTP server, register basic and parameterized routes, apply middleware, and start the server. This example showcases the core functionalities for building a web application with Ant. ```Go package main import ( "fmt" "github.com/justinwongcn/ant" "github.com/justinwongcn/ant/middleware/accesslog" ) func main() { server := ant.NewHTTPServer() // 注册路由 server.Handle("GET /hello", func(ctx *ant.Context) { ctx.WriteString("Hello, Ant!") }) // 使用参数化路由 server.Handle("GET /posts/{id}", func(ctx *ant.Context) { id := ctx.Request.PathValue("id") ctx.WriteString(fmt.Sprintf("Post ID: %s", id)) }) // 使用中间件 server.Use(accesslog.MiddlewareBuilder{}.Build()) // 启动服务器 server.Run(":8080") } ``` -------------------------------- ### Install Ant Web Framework Source: https://github.com/teanft/ant/blob/main/README.md Provides the command to install the Ant web framework using Go's package manager. ```bash go get github.com/your-username/ant ``` -------------------------------- ### Go: Basic HTTP Server with ServeMux Example Source: https://github.com/teanft/ant/blob/main/docs/ServeMux.md An example demonstrating how to initialize a `ServeMux`, register a custom `apiHandler` for a specific path prefix (`/api/`), and set up a root handler (`/`) that serves a welcome message or a 404 for other paths. This showcases fundamental HTTP routing in Go. ```Go package main import ( "fmt" "net/http" ) type apiHandler struct{} func (apiHandler) ServeHTTP(http.ResponseWriter, *http.Request) {} func main() { mux := http.NewServeMux() mux.Handle("/api/", apiHandler{}) mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { // The "/" pattern matches everything, so we need to check // that we're at the root here. if req.URL.Path != "/" { http.NotFound(w, req) return } fmt.Fprintf(w, "Welcome to the home page!") }) } ``` -------------------------------- ### Perform HTTP GET Request in Go Source: https://github.com/teanft/ant/blob/main/docs/ServeMux.md Demonstrates how to make a basic HTTP GET request to a URL using Go's `net/http` package. It includes error handling, reading the response body, and ensuring the response body is closed. The example fetches `http://www.google.com/robots.txt` and prints its content. ```Go package main import ( "fmt" "io" "log" "net/http" ) func main() { res, err := http.Get("http://www.google.com/robots.txt") if err != nil { log.Fatal(err) } body, err := io.ReadAll(res.Body) res.Body.Close() if res.StatusCode > 299 { log.Fatalf("Response failed with status code: %d and\nbody: %s\n", res.StatusCode, body) } if err != nil { log.Fatal(err) } fmt.Printf("%s", body) } ``` -------------------------------- ### Go ListenAndServeTLS Example Program Source: https://github.com/teanft/ant/blob/main/docs/ServeMux.md An example Go program demonstrating how to use `http.ListenAndServeTLS` to serve HTTPS content. It sets up a simple handler and listens on port 8443, requiring `cert.pem` and `key.pem` files for TLS. ```Go package main import ( "io" "log" "net/http" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { io.WriteString(w, "Hello, TLS!\n") }) // One can use generate_cert.go in crypto/tls to generate cert.pem and key.pem. log.Printf("About to listen on 8443. Go to https://127.0.0.1:8443/") err := http.ListenAndServeTLS(":8443", "cert.pem", "key.pem", nil) log.Fatal(err) } ``` -------------------------------- ### Go: Example HTTP Handler with Response Trailers Source: https://github.com/teanft/ant/blob/main/docs/ServeMux.md This example demonstrates how to implement an HTTP handler that sends response trailers. It shows the process of declaring trailer headers using `w.Header().Set("Trailer", ...)` before `WriteHeader()` is called, and then setting the actual trailer values later in the response body stream. ```Go package main import ( "io" "net/http" ) func main() { mux := http.NewServeMux() mux.HandleFunc("/sendstrailers", func(w http.ResponseWriter, req *http.Request) { // Before any call to WriteHeader or Write, declare // the trailers you will set during the HTTP // response. These three headers are actually sent in // the trailer. w.Header().Set("Trailer", "AtEnd1, AtEnd2") w.Header().Add("Trailer", "AtEnd3") w.Header().Set("Content-Type", "text/plain; charset=utf-8") // normal header w.WriteHeader(http.StatusOK) w.Header().Set("AtEnd1", "value 1") io.WriteString(w, "This HTTP response has both headers before this text and trailers at the end.\n") w.Header().Set("AtEnd2", "value 2") w.Header().Set("AtEnd3", "value 3") // These will appear as trailers. }) } ``` -------------------------------- ### Serve Simple Static Web Server in Go Source: https://github.com/teanft/ant/blob/main/docs/ServeMux.md Demonstrates how to set up a basic static web server in Go using `http.ListenAndServe` and `http.FileServer`. This example serves files from the `/usr/share/doc` directory on port 8080. ```Go package main import ( "log" "net/http" ) func main() { // Simple static webserver: log.Fatal(http.ListenAndServe(":8080", http.FileServer(http.Dir("/usr/share/doc")))) } ``` -------------------------------- ### Implementing Custom Session Repository in Go Source: https://github.com/teanft/ant/blob/main/session/README.md Provides an example of how to extend the session management by implementing the `SessionRepository` interface for a custom storage backend. ```go type CustomRepository struct { // Custom fields } func (r *CustomRepository) Save(ctx context.Context, session *entity.Session) error { // Implement save logic } // Implement other interface methods... ``` -------------------------------- ### Go: Start Ant HTTPServer Source: https://github.com/teanft/ant/blob/main/coverage.html Starts the HTTP server, listening on the specified address. This is a blocking call, meaning the server will continue to run until an error occurs or it is explicitly stopped. It prints a message indicating the server's listening address. ```Go // Run 启动HTTP服务器 // addr: 服务器监听地址 // 返回值: 服务器运行过程中的错误 // 注意:这是一个阻塞调用,服务器会一直运行直到出错 func (s *HTTPServer) Run(addr string) error { fmt.Printf("Server is running on %s\n", addr) return http.ListenAndServe(addr, s) } ``` -------------------------------- ### Go HTTP Client Protocol Configuration Example Source: https://github.com/teanft/ant/blob/main/docs/ServeMux.md Illustrates how to configure an `http.Client`'s transport to support both HTTP/1 and HTTP/2. It clones the default transport and then sets the desired protocols using the `Protocols` type. ```go package main import ( "log" "net/http" ) func main() { t := http.DefaultTransport.(*http.Transport).Clone() // Use either HTTP/1 and HTTP/2. t.Protocols = new(http.Protocols) t.Protocols.SetHTTP1(true) t.Protocols.SetHTTP2(true) cli := &http.Client{Transport: t} res, err := cli.Get("http://www.google.com/robots.txt") if err != nil { log.Fatal(err) } res.Body.Close() } ``` -------------------------------- ### Go HTTP Hijacker Usage Example Source: https://github.com/teanft/ant/blob/main/docs/ServeMux.md Demonstrates how to use the `http.Hijacker` interface to take control of an underlying TCP connection from an HTTP handler. It shows checking for `Hijacker` support, performing the hijack, and then direct communication over the raw connection. ```go package main import ( "fmt" "log" "net/http" ) func main() { http.HandleFunc("/hijack", func(w http.ResponseWriter, r *http.Request) { hj, ok := w.(http.Hijacker) if !ok { http.Error(w, "webserver doesn't support hijacking", http.StatusInternalServerError) return } conn, bufrw, err := hj.Hijack() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // Don't forget to close the connection: defer conn.Close() bufrw.WriteString("Now we're speaking raw TCP. Say hi: ") bufrw.Flush() s, err := bufrw.ReadString('\n') if err != nil { log.Printf("error reading string: %v", err) return } fmt.Fprintf(bufrw, "You said: %q\nBye.\n", s) bufrw.Flush() }) } ``` -------------------------------- ### HTTP Client Get Method Source: https://github.com/teanft/ant/blob/main/docs/ServeMux.md Documents the `Get` method for issuing HTTP GET requests. It details redirect handling (up to 10 redirects for 301, 302, 303, 307, 308), error conditions (too many redirects, protocol errors), and proper response body closure. It also notes it's a wrapper for `DefaultClient.Get` and suggests alternatives for custom headers or context. ```APIDOC Get(url string) (*Response, error): Description: Issues an HTTP GET request to the specified URL. Redirects: - Follows 301, 302, 303, 307, 308 redirects up to 10 times. Errors: - Returned for too many redirects or HTTP protocol errors. - Non-2xx responses do not cause an error. - Error type is *url.Error; Timeout() reports true if timed out. Body Handling: Caller must close resp.Body. Usage Notes: - Wrapper around DefaultClient.Get. - Use NewRequest and DefaultClient.Do for custom headers. - Use NewRequestWithContext and DefaultClient.Do for context. ``` -------------------------------- ### APIDOC: Ant Framework Server Configuration Options Source: https://github.com/teanft/ant/blob/main/coverage.html Defines a functional option pattern for configuring the `HTTPServer`. `ServerWithTemplateEngine` provides a way to inject a custom template engine during server initialization, allowing for flexible server setup. ```APIDOC // ServerOption 定义服务器配置选项函数类型 // server: 需要配置的HTTP服务器实例 type ServerOption func(server *HTTPServer) // ServerWithTemplateEngine 创建设置模板引擎的配置选项 // engine: 要使用的模板引擎实例 // 返回值: 配置函数 func ServerWithTemplateEngine(engine TemplateEngine) ServerOption { return func(server *HTTPServer) { server.TemplateEngine = engine } } ``` -------------------------------- ### Perform Basic HTTP Client Requests in Go Source: https://github.com/teanft/ant/blob/main/docs/ServeMux.md This snippet demonstrates how to make basic HTTP GET, POST, and POST form requests using the `http` package in Go. It shows direct calls to `http.Get`, `http.Post`, and `http.PostForm` for common web interactions. ```Go resp, err := http.Get("http://example.com/") ... resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf) ... resp, err := http.PostForm("http://example.com/form", url.Values{"key": {"Value"}, "id": {"123"}}) ``` -------------------------------- ### Configure Custom HTTP Server in Go Source: https://github.com/teanft/ant/blob/main/docs/ServeMux.md This example illustrates how to create and configure a custom `http.Server` in Go for more advanced server control. It allows setting specific timeouts, a custom handler, and maximum header size for the server. ```Go s := &http.Server{ Addr: ":8080", Handler: myHandler, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, } log.Fatal(s.ListenAndServe()) ``` -------------------------------- ### Go: Create 404 Not Found Handler and Usage Example Source: https://github.com/teanft/ant/blob/main/docs/ServeMux.md NotFoundHandler returns a simple request handler that replies to each request with a “404 page not found” reply. The example demonstrates how to integrate it into a `http.ServeMux` alongside a custom handler. ```APIDOC func NotFoundHandler() Handler ``` ```Go package main import ( "fmt" "log" "net/http" ) func newPeopleHandler() http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "This is the people handler.") }) } func main() { mux := http.NewServeMux() // Create sample handler to returns 404 mux.Handle("/resources", http.NotFoundHandler()) // Create sample handler that returns 200 mux.Handle("/resources/people/", newPeopleHandler()) log.Fatal(http.ListenAndServe(":8080", mux)) } ``` -------------------------------- ### APIDOC: http.ServeMux Request Multiplexer Source: https://github.com/teanft/ant/blob/main/docs/ServeMux.md `ServeMux` is an HTTP request multiplexer that matches the URL of each incoming request against a list of registered patterns and calls the handler for the pattern that most closely matches the URL. Patterns can match the method, host, and path of a request. Examples include: "/index.html", "GET /static/", "example.com/", "example.com/{$}", and "/b/{bucket}/o/{objectname...}". All three parts (METHOD, HOST, PATH) are optional; "/" is a valid pattern. If METHOD is present, it must be followed by at least one space or tab. Literal parts of a pattern match case-sensitively. A pattern with no method matches every method; GET matches GET and HEAD. A pattern with no host matches every host. A path can include wildcard segments like `{NAME}` or `{NAME...}`. Wildcards must be full path segments. A `...` wildcard matches the remainder of the URL path. The special wildcard `{$}` matches only the end of the URL. For matching, both pattern paths and incoming request paths are unescaped segment by segment. ```APIDOC [METHOD ][HOST]/[PATH] ``` -------------------------------- ### Go: Example NewFileTransport Usage Source: https://github.com/teanft/ant/blob/main/docs/ServeMux.md Illustrates a typical way to initialize an `http.Transport` in Go. While this snippet is brief, it sets the context for how `NewFileTransport` might be integrated, often by assigning it to a `Transport` field or using it to handle specific URL schemes. ```Go t := &http.Transport{} ``` -------------------------------- ### Go net/http ListenAndServe Function Source: https://github.com/teanft/ant/blob/main/docs/ServeMux.md Starts an HTTP server that listens on a specified TCP address and handles incoming requests. It explains the role of the handler (defaulting to `DefaultServeMux`) and notes that the function always returns a non-nil error upon termination. ```APIDOC func ListenAndServe(addr string, handler Handler) error ListenAndServe listens on the TCP network address addr and then calls Serve with handler to handle requests on incoming connections. Accepted connections are configured to enable TCP keep-alives. The handler is typically nil, in which case DefaultServeMux is used. ListenAndServe always returns a non-nil error. ``` ```Go package main import ( "io" "log" "net/http" ) func main() { // Hello world, the web server helloHandler := func(w http.ResponseWriter, req *http.Request) { io.WriteString(w, "Hello, world!\n") } http.HandleFunc("/hello", helloHandler) log.Fatal(http.ListenAndServe(":8080", nil)) } ``` -------------------------------- ### Go HTTP HandleFunc for Basic Path Matching (Pre-Go 1.22) Source: https://github.com/teanft/ant/blob/main/docs/routing-enhancements.md This Go snippet demonstrates the traditional way to handle requests for a path prefix using `http.HandleFunc` before Go 1.22. It routes all requests starting with `/posts/` to the `handlePost` function, requiring manual method checking and ID extraction within the handler. ```Go http.HandleFunc("/posts/", handlePost) ``` -------------------------------- ### Go HTTP HandleFunc with Method Matching and Wildcard (Go 1.22+) Source: https://github.com/teanft/ant/blob/main/docs/routing-enhancements.md This Go 1.22+ snippet shows how to use `http.HandleFunc` with method matching and a wildcard. The pattern `GET /posts/{id}` specifically matches GET requests to paths like `/posts/234`, automatically handling method validation and allowing direct extraction of the `id` using `req.PathValue`. ```Go http.HandleFunc("GET /posts/{id}", handlePost2) ``` -------------------------------- ### Go HTTP Server Restricting Protocols Example Source: https://github.com/teanft/ant/blob/main/docs/ServeMux.md Demonstrates how to configure an `http.Server` to explicitly support only HTTP/1.0 and HTTP/1.1 protocols. This is achieved by initializing `srv.Protocols` and calling `SetHTTP1(true)`. ```go package main import ( "log" "net/http" ) func main() { srv := http.Server{ Addr: ":8443", } // Serve only HTTP/1. srv.Protocols = new(http.Protocols) srv.Protocols.SetHTTP1(true) log.Fatal(srv.ListenAndServeTLS("cert.pem", "key.pem")) } ``` -------------------------------- ### Configure Go CookieSessionPropagator with Options Source: https://github.com/teanft/ant/blob/main/session/infrastructure/README.md Example of initializing CookieSessionPropagator using functional options to set custom cookie name and various HTTP cookie attributes like HttpOnly, Secure, SameSite, Path, and Domain. ```Go // Create propagator propagator := NewCookieSessionPropagator( WithCookieName("custom_session"), WithCookieOption(func(c *http.Cookie) { c.HttpOnly = true c.Secure = true c.SameSite = http.SameSiteStrictMode c.Path = "/" c.Domain = "example.com" }), ) ``` -------------------------------- ### Configure Custom HTTP Transport in Go Source: https://github.com/teanft/ant/blob/main/docs/ServeMux.md This example demonstrates how to customize the underlying `http.Transport` for an HTTP client in Go. It allows fine-tuning network-level settings such as connection pooling, idle timeouts, and compression behavior. ```Go tr := &http.Transport{ MaxIdleConns: 10, IdleConnTimeout: 30 * time.Second, DisableCompression: true, } client := &http.Client{Transport: tr} resp, err := client.Get("https://example.com") ``` -------------------------------- ### Go net/http Handle Function Source: https://github.com/teanft/ant/blob/main/docs/ServeMux.md Registers an `http.Handler` for a specific URL pattern with the `DefaultServeMux`. It explains how patterns are matched and provides a practical example of a concurrent counter handler. ```APIDOC func Handle(pattern string, handler Handler) ``` ```Go package main import ( "fmt" "log" "net/http" "sync" ) type countHandler struct { mu sync.Mutex // guards n n int } func (h *countHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { h.mu.Lock() defer h.mu.Unlock() h.n++ fmt.Fprintf(w, "count is %d\n", h.n) } func main() { http.Handle("/count", new(countHandler)) log.Fatal(http.ListenAndServe(":8080", nil)) } ``` -------------------------------- ### Go net/http.Server: Graceful Shutdown Example Source: https://github.com/teanft/ant/blob/main/docs/ServeMux.md This Go program demonstrates how to implement a graceful shutdown for an `http.Server`. It sets up a signal handler to catch interrupt signals (like Ctrl+C) and then calls `srv.Shutdown()` to gracefully close connections, ensuring the program waits until all idle connections are closed before exiting. ```Go package main import ( "context" "log" "net/http" "os" "os/signal" ) func main() { var srv http.Server idleConnsClosed := make(chan struct{}) go func() { sigint := make(chan os.Signal, 1) signal.Notify(sigint, os.Interrupt) <-sigint // We received an interrupt signal, shut down. if err := srv.Shutdown(context.Background()); err != nil { // Error from closing listeners, or context timeout: log.Printf("HTTP server Shutdown: %v", err) } close(idleConnsClosed) }() if err := srv.ListenAndServe(); err != http.ErrServerClosed { // Error starting or closing listener: log.Fatalf("HTTP server ListenAndServe: %v", err) } <-idleConnsClosed } ``` -------------------------------- ### Serve Directory Under Alternate URL Path with http.StripPrefix in Go Source: https://github.com/teanft/ant/blob/main/docs/ServeMux.md Illustrates how to use `http.StripPrefix` to serve a local directory under a different URL path. This is useful when the internal file system structure doesn't match the desired external URL structure. The provided snippet shows the setup for `StripPrefix`. ```Go package main import ( "net/http" ) func main() { // To serve a directory on disk (/tmp) under an alternate URL // path (/tmpfiles/), use StripPrefix to modify the request // URL's path before the FileServer sees it: ``` -------------------------------- ### Go HTTP FileServer Function and Usage Source: https://github.com/teanft/ant/blob/main/docs/ServeMux.md Returns a handler that serves HTTP requests with the contents of a specified file system. It includes a special case for redirecting '/index.html' and advises using `http.Dir` for the operating system's file system or `http.FileServerFS` for `fs.FS` implementations. An example demonstrates serving files from `/tmp`. ```APIDOC func FileServer(root FileSystem) Handler ``` ```Go http.Handle("/", http.FileServer(http.Dir("/tmp"))) ``` -------------------------------- ### Go: Remove URL Prefix with StripPrefix Source: https://github.com/teanft/ant/blob/main/docs/ServeMux.md StripPrefix returns a handler that serves HTTP requests by removing the given prefix from the request URL's Path (and RawPath if set) and invoking the handler h. StripPrefix handles a request for a path that doesn't begin with prefix by replying with an HTTP 404 not found error. The prefix must match exactly: if the prefix in the request contains escaped characters the reply is also an HTTP 404 not found error. The example demonstrates serving a local directory under an alternate URL path. ```APIDOC func StripPrefix(prefix string, h Handler) Handler ``` ```Go package main import ( "net/http" ) func main() { // To serve a directory on disk (/tmp) under an alternate URL // path (/tmpfiles/), use StripPrefix to modify the request // URL's path before the FileServer sees it: http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp")))) } ``` -------------------------------- ### Create Basic HTTP Server with Default Mux in Go Source: https://github.com/teanft/ant/blob/main/docs/ServeMux.md This snippet shows how to set up a basic HTTP server in Go using `http.ListenAndServe` and the default serve multiplexer. It demonstrates registering handlers for specific paths using `http.Handle` and `http.HandleFunc`. ```Go http.Handle("/foo", fooHandler) http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path)) }) log.Fatal(http.ListenAndServe(":8080", nil)) ``` -------------------------------- ### Implement Custom Go HTTP FileSystem to Hide Dot Files Source: https://github.com/teanft/ant/blob/main/docs/ServeMux.md Provides a comprehensive example of creating a custom `http.FileSystem` (`dotFileHidingFileSystem`) that prevents 'dot files' (files or directories starting with '.') from being served. It includes helper functions (`containsDotFile`, `dotFileHidingFile`) to wrap `http.File` and `http.FileSystem` methods, ensuring hidden files are filtered out or result in a 403 error. ```Go package main import ( "io" "io/fs" "log" "net/http" "strings" ) // containsDotFile reports whether name contains a path element starting with a period. // The name is assumed to be a delimited by forward slashes, as guaranteed // by the http.FileSystem interface. func containsDotFile(name string) bool { parts := strings.Split(name, "/") for _, part := range parts { if strings.HasPrefix(part, ".") { return true } } return false } // dotFileHidingFile is the http.File use in dotFileHidingFileSystem. // It is used to wrap the Readdir method of http.File so that we can // remove files and directories that start with a period from its output. type dotFileHidingFile struct { http.File } // Readdir is a wrapper around the Readdir method of the embedded File // that filters out all files that start with a period in their name. func (f dotFileHidingFile) Readdir(n int) (fis []fs.FileInfo, err error) { files, err := f.File.Readdir(n) for _, file := range files { // Filters out the dot files if !strings.HasPrefix(file.Name(), ".") { fis = append(fis, file) } } if err == nil && n > 0 && len(fis) == 0 { err = io.EOF } return } // dotFileHidingFileSystem is an http.FileSystem that hides // hidden "dot files" from being served. type dotFileHidingFileSystem struct { http.FileSystem } // Open is a wrapper around the Open method of the embedded FileSystem // that serves a 403 permission error when name has a file or directory // with whose name starts with a period in its path. func (fsys dotFileHidingFileSystem) Open(name string) (http.File, error) { if containsDotFile(name) { // If dot file, return 403 response return nil, fs.ErrPermission } file, err := fsys.FileSystem.Open(name) if err != nil { return nil, err } return dotFileHidingFile{file}, err } func main() { fsys := dotFileHidingFileSystem{http.Dir(".")} http.Handle("/", http.FileServer(fsys)) log.Fatal(http.ListenAndServe(":8080", nil)) } ``` -------------------------------- ### Basic Session Manager Usage in Go Source: https://github.com/teanft/ant/blob/main/session/README.md Demonstrates how to initialize and use the session manager in a Go application, including setting up repository, propagator, application service, and the manager itself. ```go package main import ( "time" "github.com/justinwongcn/ant/session/application/service" "github.com/justinwongcn/ant/session/infrastructure/repository" "github.com/justinwongcn/ant/session/infrastructure/propagator" "github.com/justinwongcn/ant/session/interface/manager" ) func main() { // Create infrastructure components sessionRepo := repository.NewMemorySessionRepository(30*time.Minute, 5*time.Minute) sessionProp := propagator.NewCookieSessionPropagator() // Create application service appService := service.NewSessionApplicationService(sessionRepo, sessionProp) // Create session manager sessionManager := manager.NewSessionManager(appService, "session") // Use in HTTP handler // session, err := sessionManager.GetSession(ctx) // if err != nil { // // Create new session // session, err = sessionManager.InitSession(ctx, "", 30*time.Minute) // } } ``` -------------------------------- ### Go: Create New Ant HTTPServer Instance Source: https://github.com/teanft/ant/blob/main/coverage.html Initializes a new `HTTPServer` instance. It accepts optional `ServerOption` functions to configure the server, such as setting a template engine. By default, no middleware is included and must be registered via the `Use` method. ```Go // NewHTTPServer 创建一个新的HTTP服务器实例 // opts: 可选的服务器配置选项 // 返回值: 初始化后的HTTPServer指针 // 注意:默认不包含任何中间件,需要通过Use方法注册 func NewHTTPServer(opts ...ServerOption) *HTTPServer { server := &HTTPServer{ mux: http.NewServeMux(), middlewares: make([]Middleware, 0), } // 应用所有配置选项 for _, opt := range opts { opt(server) } return server } ``` -------------------------------- ### Go HTTP Package API Reference Source: https://github.com/teanft/ant/blob/main/docs/ServeMux.md Comprehensive API documentation for core HTTP types and their associated methods, including controllers, writers, transports, multiplexers, and server functionalities. It details how to set deadlines, handle requests, manage connections, and configure HTTP servers. ```APIDOC ResponseController: SetReadDeadline(deadline time.Time) error SetWriteDeadline(deadline time.Time) error ResponseWriter: type RoundTripper: type NewFileTransport(fs FileSystem) RoundTripper NewFileTransportFS(fsys fs.FS) RoundTripper SameSite: type ServeMux: type NewServeMux() *ServeMux Handle(pattern string, handler Handler) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) Handler(r *Request) (h Handler, pattern string) ServeHTTP(w ResponseWriter, r *Request) Server: type Close() error ListenAndServe() error ListenAndServeTLS(certFile, keyFile string) error RegisterOnShutdown(f func()) Serve(l net.Listener) error ServeTLS(l net.Listener, certFile, keyFile string) error SetKeepAlivesEnabled(v bool) Shutdown(ctx context.Context) error Transport: type CancelRequest(req *Request) (deprecated) Clone() *Transport CloseIdleConnections() RegisterProtocol(scheme string, rt RoundTripper) RoundTrip(req *Request) (*Response, error) ``` -------------------------------- ### GoTemplateEngine Struct API Documentation Source: https://github.com/teanft/ant/blob/main/coverage.html API documentation for the `GoTemplateEngine` struct and its methods, providing an interface for managing and rendering Go templates. ```APIDOC GoTemplateEngine: T: *template.Template Description: The underlying template object. Uses a single Template instance instead of a map, as Template itself supports indexing sub-templates by name. Render(ctx context.Context, tplName string, data any) ([]byte, error) Description: Renders data into the specified template and returns the rendered result. Preserves RespData semantics to allow middleware to modify the rendering result. Parameters: ctx: context.Context - Context object for controlling the rendering process. tplName: string - The name of the template to render. data: any - Data required for rendering. Returns: []byte: The rendered page content. error: Error during the rendering process. LoadFromGlob(pattern string) error Description: Loads templates from the specified glob pattern. Parameters: pattern: string - Glob pattern string for matching template files. Returns: error: Error encountered during loading. LoadFromFiles(files ...string) error Description: Loads templates from the specified list of files. Parameters: files: ...string - List of template file paths. Returns: error: Error encountered during loading. LoadFromFS(fs fs.FS, paths ...string) error Description: Loads templates from the file system interface. Parameters: fs: fs.FS - File system interface for accessing template files. paths: ...string - Paths of template files within the file system. Returns: error: Error encountered during loading. ``` -------------------------------- ### Get Raw String Value from StringValue in Go Source: https://github.com/teanft/ant/blob/main/coverage.html Retrieves the raw string value and any associated error from the `StringValue` wrapper. ```Go // String gets the raw string value and any potential error. func (s StringValue) String() (string, error) { return s.val, s.err } ``` -------------------------------- ### Go Factory Pattern for Infrastructure Instance Creation Source: https://github.com/teanft/ant/blob/main/session/infrastructure/README.md Illustrates the Factory pattern with factory functions NewMemorySessionRepository and NewCookieSessionPropagator for creating configured instances of repository and propagator implementations. ```Go func NewMemorySessionRepository(expiration, cleanupInterval time.Duration) repository.SessionRepository { return &MemorySessionRepository{ cache: cache.New(expiration, cleanupInterval), expiration: expiration, } } func NewCookieSessionPropagator(opts ...func(*CookieSessionPropagator)) repository.SessionPropagator { p := &CookieSessionPropagator{ cookieName: "sessid", cookieOption: func(c *http.Cookie) {}, } for _, opt := range opts { opt(p) } return p } ``` -------------------------------- ### Session Entity Core Methods (Go) Source: https://github.com/teanft/ant/blob/main/session/domain/README.md Defines the primary methods for the Session entity, including creation, data manipulation (Get, Set, Delete), and time management (IsExpired, Refresh, SetExpiration). ```go // 创建新会话 func NewSession(id SessionID, expiration time.Duration) *Session // 数据操作 func (s *Session) Get(ctx context.Context, key string) (any, error) func (s *Session) Set(ctx context.Context, key string, value any) error func (s *Session) Delete(ctx context.Context, key string) error // 时间管理 func (s *Session) IsExpired() bool func (s *Session) Refresh() func (s *Session) SetExpiration(expiration time.Duration) ``` -------------------------------- ### Go net/http Client API Reference Source: https://github.com/teanft/ant/blob/main/docs/ServeMux.md Detailed API documentation for the Go `net/http.Client` type, including its general behavior, method descriptions, and specific handling of HTTP features like redirects and connection management. ```APIDOC Client: Description: A Client is a higher-level HTTP client that handles details such as cookies and redirects. Clients should be reused for efficiency due to internal state (e.g., cached TCP connections) and are safe for concurrent use by multiple goroutines. Redirect Behavior: - Forwards all headers set on the initial Request except sensitive ones (Authorization, WWW-Authenticate, Cookie) to untrusted targets (domains not a subdomain or exact match of initial domain). - When forwarding 'Cookie' header with a non-nil cookie Jar, mutated cookies are omitted, expecting the Jar to insert updated values. If Jar is nil, initial cookies are forwarded unchanged. Methods: CloseIdleConnections(): Description: Closes any connections on its Transport that are idle in a 'keep-alive' state. Does not interrupt connections in use. If Client.Transport does not have a CloseIdleConnections method, this does nothing. Do(req *Request) (*Response, error): Description: Sends an HTTP request and returns an HTTP response, following client policy (redirects, cookies, auth). Generally, Get, Post, or PostForm are preferred. Errors: - Returned if caused by client policy (e.g., CheckRedirect) or failure to speak HTTP (e.g., network connectivity). - A non-2xx status code does not cause an error. - Any returned error will be of type *url.Error. The url.Error value's Timeout method reports true if the request timed out. Response Body: - If error is nil, Response will contain a non-nil Body which must be closed by the user. Failure to read to EOF and close Body may prevent connection reuse. - Request Body, if non-nil, will be closed by the underlying Transport, even on errors, possibly asynchronously. - On error, any Response can be ignored. A non-nil Response with a non-nil error only occurs when CheckRedirect fails, and the Response.Body is already closed. Redirect Logic: - Uses CheckRedirect function to determine if redirect should be followed. - 301, 302, 303 redirects: Subsequent requests use HTTP method GET (or HEAD if original was HEAD), with no body. - 307, 308 redirects: Preserve original HTTP method and body, provided Request.GetBody function is defined (NewRequest sets GetBody for common standard library body types). Get(url string) (*Response, error): Description: Issues a GET request to the specified URL. Follows redirects after calling Client.CheckRedirect. Redirect Codes Followed: - 301 (Moved Permanently) - 302 (Found) - 303 (See Other) - 307 (Temporary Redirect) - 308 (Permanent Redirect) Errors: - Returned if Client.CheckRedirect function fails or if there was an HTTP protocol error. A non-2xx response doesn't cause an error. - Any returned error will be of type *url.Error. The url.Error value's Timeout method reports true if the request timed out. Response Body: - When err is nil, resp always contains a non-nil resp.Body. Caller should close resp.Body when done reading from it. Customization: - For custom headers: Use NewRequest and Client.Do. - For specified context.Context: Use NewRequestWithContext and Client.Do. Head(url string) (*Response, error): Description: Issues a HEAD request to the specified URL. Follows redirects after calling Client.CheckRedirect. Redirect Codes Followed: - 301 (Moved Permanently) - 302 (Found) - 303 (See Other) - 307 (Temporary Redirect) - 308 (Permanent Redirect) Customization: - For specified context.Context: Use NewRequestWithContext and Client.Do. Post(url, contentType string, body io.Reader) (*Response, error): Description: Issues a POST request to the specified URL. ``` -------------------------------- ### Initialize Go Static Resource Handler Source: https://github.com/teanft/ant/blob/main/coverage.html Initializes a new `StaticResourceHandler` instance. It sets up default MIME types for common file extensions (e.g., jpeg, png, pdf, txt) and applies configuration options provided by `StaticResourceHandlerOption` functions. This handler is designed to serve static files efficiently. ```Go func NewStaticResourceHandler(dir string, options ...StaticResourceHandlerOption) *StaticResourceHandler { h := &StaticResourceHandler{ dir: dir, extensionContentTypeMap: map[string]string{ "jpeg": "image/jpeg", "jpg": "image/jpeg", "png": "image/png", "gif": "image/gif", "ico": "image/x-icon", "svg": "image/svg+xml", "pdf": "application/pdf", "txt": "text/plain" } } for _, opt := range options { opt(h) } return h } ``` -------------------------------- ### Go: Get File Extension from Filename Source: https://github.com/teanft/ant/blob/main/coverage.html Extracts the file extension from a given filename. It returns an empty string if no extension is found or if the filename ends with a dot. The returned extension does not include the leading dot. ```Go // getFileExt 获取文件名中的扩展名 // name: 完整的文件名 // 返回值: 文件扩展名(不包含点号),如果没有扩展名则返回空字符串 func getFileExt(name string) string { index := strings.LastIndex(name, ".") if index == len(name)-1 { return "" } return name\[index+1:\] } ``` -------------------------------- ### Load Go Templates from File System Interface Source: https://github.com/teanft/ant/blob/main/coverage.html Loads templates into the `GoTemplateEngine` from a given `fs.FS` interface and a list of paths within that file system. This provides flexibility for loading templates from various file system implementations. ```Go // LoadFromFS 从文件系统加载模板 // fs: 文件系统接口,用于访问模板文件 // paths: 模板文件在文件系统中的路径列表 // 返回值: 加载过程中发生的错误 func (g *GoTemplateEngine) LoadFromFS(fs fs.FS, paths ...string) error { var err error g.T, err = template.ParseFS(fs, paths...) return err } ``` -------------------------------- ### Get URL Path Parameter from HTTP Request in Go Context Source: https://github.com/teanft/ant/blob/main/coverage.html Retrieves the value of a specified key from the URL path parameters. Returns the value wrapped in a `StringValue` struct, or an error if the key is not found. ```Go // PathValue gets the value for the specified key from the URL path parameters. // // key parameter specifies the name of the path parameter to retrieve. // // Returns a StringValue type, containing the path parameter's value or error information. func (c *Context) PathValue(key string) StringValue { value := c.Req.PathValue(key) if value == "" { return StringValue{err: errors.New("web: key not found")} } return StringValue{val: value} } ``` -------------------------------- ### Go Strategy Pattern for Session Repository Selection Source: https://github.com/teanft/ant/blob/main/session/infrastructure/README.md Demonstrates the Strategy pattern by dynamically selecting different SessionRepository implementations (memory, Redis, database) based on a storageType variable. ```Go // Can choose different storage strategies var repo repository.SessionRepository switch storageType { case "memory": repo = NewMemorySessionRepository(expiration, cleanupInterval) case "redis": repo = NewRedisSessionRepository(redisClient) case "database": repo = NewDatabaseSessionRepository(db) } ``` -------------------------------- ### Load Go Templates from Specific Files Source: https://github.com/teanft/ant/blob/main/coverage.html Loads templates into the `GoTemplateEngine` from a list of explicitly provided file paths. This is useful for loading a fixed set of template files. ```Go // LoadFromFiles 从指定的文件列表加载模板 // files: 模板文件路径列表 // 返回值: 加载过程中发生的错误 func (g *GoTemplateEngine) LoadFromFiles(files ...string) error { var err error g.T, err = template.ParseFiles(files...) return err } ``` -------------------------------- ### Optimize Memory with Session Object Pool Source: https://github.com/teanft/ant/blob/main/session/infrastructure/README.md Illustrates memory optimization for a session repository using `sync.Pool` to reduce garbage collection overhead. The `OptimizedMemoryRepository` provides methods to efficiently reuse `entity.Session` objects by getting them from and putting them back into the pool after clearing their state. ```Go // 优化的内存仓储 type OptimizedMemoryRepository struct { cache *cache.Cache sessionPool sync.Pool // 对象池 } func (r *OptimizedMemoryRepository) getSession() *entity.Session { if session := r.sessionPool.Get(); session != nil { return session.(*entity.Session) } return &entity.Session{} } func (r *OptimizedMemoryRepository) putSession(session *entity.Session) { // 重置会话状态 session.Clear() r.sessionPool.Put(session) } ``` -------------------------------- ### APIDOC: Go http.ServeTLS Function Source: https://github.com/teanft/ant/blob/main/docs/ServeMux.md Documents the `ServeTLS` function in Go's `net/http` package, which accepts incoming HTTPS connections. It explains the role of the handler (defaulting to `DefaultServeMux`) and the requirement for providing certificate and private key files for secure communication, noting that it always returns a non-nil error. ```APIDOC func ServeTLS ServeTLS accepts incoming HTTPS connections on the listener l, creating a new service goroutine for each. The service goroutines read requests and then call handler to reply to them. The handler is typically nil, in which case DefaultServeMux is used. Additionally, files containing a certificate and matching private key for the server must be provided. If the certificate is signed by a certificate authority, the certFile should be the concatenation of the server's certificate, any intermediates, and the CA's certificate. ServeTLS always returns a non-nil error. ``` -------------------------------- ### Go: Implement http.Handler for Ant HTTPServer Source: https://github.com/teanft/ant/blob/main/coverage.html Implements the `http.Handler` interface, making `HTTPServer` compatible with standard Go HTTP servers. It serves as the entry point for all incoming HTTP requests, delegating to the underlying `http.ServeMux`. ```Go // ServeHTTP 实现http.Handler接口 // 作为HTTP服务器的请求处理入口 func (s *HTTPServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { s.mux.ServeHTTP(w, r) } ``` -------------------------------- ### Get URL Query Parameter with Default Value in Go Context Source: https://github.com/teanft/ant/blob/main/coverage.html Retrieves the value of a specified key from the URL query parameters. If the key is not found, it returns the provided default value. It caches the parsed query values for efficiency. ```Go // DefaultQueryValue gets the value for the specified key from the URL query parameters, returning a default value if not found. // // key parameter specifies the name of the query parameter to retrieve. // defaultValue parameter specifies the default value to use if the parameter is not found. // // Returns a StringValue type, containing the query parameter's value or the default value. func (c *Context) DefaultQueryValue(key string, defaultValue string) StringValue { if c.cacheQueryValues == nil { c.cacheQueryValues = c.Req.URL.Query() } value := c.cacheQueryValues.Get(key) if value == "" { return StringValue{val: defaultValue} } return StringValue{val: value} } ```