libNetHttp

package
v0.28.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 11, 2026 License: MIT Imports: 19 Imported by: 0

README

Net/HTTP Web Framework Support for requestCore

This package provides support for Go's standard net/http package as a web framework in the requestCore ecosystem.

Features

  • ✅ Full compatibility with requestCore's RequestParser interface
  • ✅ Support for all standard HTTP methods (GET, POST, PUT, DELETE, PATCH)
  • ✅ Built-in middleware support (CORS, Logging, Recovery, Auth)
  • ✅ File upload and download capabilities
  • ✅ Cookie handling
  • ✅ URL parameter and query parameter extraction
  • ✅ JSON request/response handling
  • ✅ Form data parsing
  • ✅ Custom error handling
  • ✅ Static file serving
  • ✅ Redirect support

Quick Start

Basic Server Setup
package main

import (
    "log"
    "net/http"
    
    "github.com/hmmftg/requestCore/libNetHttp"
)

func main() {
    // Create a server with requestCore integration
    server := libNetHttp.CreateExampleServer()
    
    log.Println("Starting server on :8080")
    log.Fatal(server.ListenAndServe())
}
Custom Handler with requestCore
func MyHandler(w http.ResponseWriter, r *http.Request) {
    // Initialize requestCore context
    wf := libContext.InitNetHttpContext(r, w, false)
    parser := wf.Parser.(libNetHttp.NetHttpParser)
    
    // Get request information
    method := parser.GetMethod()
    path := parser.GetPath()
    
    // Parse JSON body
    var requestData MyRequestStruct
    err := parser.GetBody(&requestData)
    if err != nil {
        http.Error(w, "Invalid JSON", http.StatusBadRequest)
        return
    }
    
    // Process request...
    
    // Send JSON response
    response := MyResponseStruct{
        Message: "Success",
        Data:    requestData,
    }
    
    parser.SendJSONRespBody(http.StatusOK, response)
}

Middleware

Built-in Middleware
// Chain multiple middleware
handler := libNetHttp.ChainMiddleware(
    libNetHttp.LoggingMiddleware(),
    libNetHttp.CORSMiddleware(),
    libNetHttp.RecoveryMiddleware(),
    libNetHttp.AuthMiddleware(),
)

mux.HandleFunc("/api/endpoint", handler(http.HandlerFunc(MyHandler)).ServeHTTP)
Custom Middleware
func CustomMiddleware() libNetHttp.Middleware {
    return func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            // Pre-processing
            log.Println("Before handler")
            
            // Call next middleware/handler
            next.ServeHTTP(w, r)
            
            // Post-processing
            log.Println("After handler")
        })
    }
}

Request Parsing

JSON Body Parsing
type UserRequest struct {
    Name  string `json:"name"`
    Email string `json:"email"`
}

func CreateUser(w http.ResponseWriter, r *http.Request) {
    wf := libContext.InitNetHttpContext(r, w, false)
    parser := wf.Parser.(libNetHttp.NetHttpParser)
    
    var user UserRequest
    err := parser.GetBody(&user)
    if err != nil {
        http.Error(w, "Invalid JSON", http.StatusBadRequest)
        return
    }
    
    // Process user creation...
}
URL Parameters
func GetUser(w http.ResponseWriter, r *http.Request) {
    wf := libContext.InitNetHttpContext(r, w, false)
    parser := wf.Parser.(libNetHttp.NetHttpParser)
    
    // Set URL parameters (typically done by your router)
    parser.AddParam("id", "123")
    
    // Get parameter
    userID := parser.GetUrlParam("id")
    
    // Get all parameters
    params := parser.GetUrlParams()
}
Query Parameters
func SearchUsers(w http.ResponseWriter, r *http.Request) {
    wf := libContext.InitNetHttpContext(r, w, false)
    parser := wf.Parser.(libNetHttp.NetHttpParser)
    
    // Parse query parameters into struct
    type SearchParams struct {
        Query string `json:"q"`
        Limit int    `json:"limit"`
    }
    
    var searchParams SearchParams
    err := parser.GetUrlQuery(&searchParams)
    if err != nil {
        http.Error(w, "Invalid query parameters", http.StatusBadRequest)
        return
    }
    
    // Process search...
}
Form Data
func HandleForm(w http.ResponseWriter, r *http.Request) {
    wf := libContext.InitNetHttpContext(r, w, false)
    parser := wf.Parser.(libNetHttp.NetHttpParser)
    
    // Parse form data
    err := parser.ParseForm()
    if err != nil {
        http.Error(w, "Error parsing form", http.StatusBadRequest)
        return
    }
    
    // Get form values
    name := parser.GetFormValue("name")
    email := parser.GetFormValue("email")
    
    // Get all values for a key
    tags := parser.GetFormValues("tags")
}

File Operations

File Upload
func UploadFile(w http.ResponseWriter, r *http.Request) {
    wf := libContext.InitNetHttpContext(r, w, false)
    parser := wf.Parser.(libNetHttp.NetHttpParser)
    
    // Parse multipart form
    err := parser.ParseMultipartForm(32 << 20) // 32 MB max
    if err != nil {
        http.Error(w, "Error parsing multipart form", http.StatusBadRequest)
        return
    }
    
    // Save uploaded file
    err = parser.SaveFile("file", "/uploads/uploaded_file.txt")
    if err != nil {
        http.Error(w, "Error saving file", http.StatusInternalServerError)
        return
    }
    
    // Response
    response := map[string]string{
        "message": "File uploaded successfully",
    }
    parser.SendJSONRespBody(http.StatusOK, response)
}
File Download
func DownloadFile(w http.ResponseWriter, r *http.Request) {
    wf := libContext.InitNetHttpContext(r, w, false)
    parser := wf.Parser.(libNetHttp.NetHttpParser)
    
    // Serve file as attachment
    parser.FileAttachment("/path/to/file.pdf", "document.pdf")
}
func HandleCookies(w http.ResponseWriter, r *http.Request) {
    wf := libContext.InitNetHttpContext(r, w, false)
    parser := wf.Parser.(libNetHttp.NetHttpParser)
    
    // Get all cookies
    cookies := parser.GetCookies()
    
    // Get specific cookie
    sessionCookie, err := parser.GetCookie("session")
    if err != nil {
        // Cookie not found
    }
    
    // Set new cookie
    cookie := &http.Cookie{
        Name:    "user_preference",
        Value:   "dark_mode",
        Expires: time.Now().Add(24 * time.Hour),
        Path:    "/",
    }
    parser.SetCookie(cookie)
}

Error Handling

func ErrorHandler(w http.ResponseWriter, r *http.Request) {
    wf := libContext.InitNetHttpContext(r, w, false)
    parser := wf.Parser.(libNetHttp.NetHttpParser)
    
    // Custom error response
    errorResponse := map[string]string{
        "error":   "Custom error message",
        "code":    "CUSTOM_ERROR",
        "details": "Additional error details",
    }
    
    parser.SendJSONRespBody(http.StatusBadRequest, errorResponse)
}

Integration with BaseHandler

If you're using requestCore's BaseHandler, you can integrate it like this:

func CreateServerWithBaseHandler() *http.Server {
    mux := http.NewServeMux()
    
    // Add middleware
    handler := libNetHttp.ChainMiddleware(
        libNetHttp.LoggingMiddleware(),
        libNetHttp.CORSMiddleware(),
        libNetHttp.RecoveryMiddleware(),
    )
    
    // Wrap BaseHandler with NetHttpHandler
    mux.HandleFunc("/api/users", handler(libNetHttp.NetHttpHandler(
        handlers.BaseHandler(core, userHandler, false)
    )).ServeHTTP)
    
    return &http.Server{
        Addr:    ":8080",
        Handler: mux,
    }
}

Testing

Unit Testing
func TestMyHandler(t *testing.T) {
    // Create test request
    req := httptest.NewRequest("GET", "/api/test", nil)
    req.Header.Set("User-Id", "test-user")
    
    // Create response recorder
    w := httptest.NewRecorder()
    
    // Call handler
    MyHandler(w, req)
    
    // Assertions
    assert.Equal(t, http.StatusOK, w.Code)
    
    var response map[string]interface{}
    err := json.Unmarshal(w.Body.Bytes(), &response)
    assert.NoError(t, err)
    assert.Equal(t, "Success", response["message"])
}

Performance Considerations

  • Use connection pooling for database connections
  • Implement proper caching strategies
  • Use http.ServeMux for simple routing or consider gorilla/mux for complex routing
  • Enable HTTP/2 for better performance
  • Use middleware sparingly to avoid overhead

Comparison with Other Frameworks

Feature net/http Gin Fiber
Performance High High Very High
Memory Usage Low Medium Low
Learning Curve Medium Low Low
Ecosystem Large Large Growing
Built-in Features Basic Rich Rich
Middleware Manual Built-in Built-in

Best Practices

  1. Use middleware for cross-cutting concerns (logging, auth, CORS)
  2. Validate input early in your handlers
  3. Use proper HTTP status codes
  4. Implement proper error handling
  5. Use context for request-scoped values
  6. Implement graceful shutdown
  7. Use structured logging
  8. Add health check endpoints

Example Complete Server

package main

import (
    "log"
    "net/http"
    "os"
    "os/signal"
    "syscall"
    "time"
    
    "github.com/hmmftg/requestCore/libNetHttp"
)

func main() {
    // Create server
    server := &http.Server{
        Addr:    ":8080",
        Handler: createHandler(),
    }
    
    // Start server in goroutine
    go func() {
        log.Println("Starting server on :8080")
        if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
            log.Fatalf("Server failed to start: %v", err)
        }
    }()
    
    // Wait for interrupt signal
    quit := make(chan os.Signal, 1)
    signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
    <-quit
    
    log.Println("Shutting down server...")
    
    // Graceful shutdown
    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()
    
    if err := server.Shutdown(ctx); err != nil {
        log.Fatalf("Server forced to shutdown: %v", err)
    }
    
    log.Println("Server exited")
}

func createHandler() http.Handler {
    mux := http.NewServeMux()
    
    // Add middleware
    handler := libNetHttp.ChainMiddleware(
        libNetHttp.LoggingMiddleware(),
        libNetHttp.CORSMiddleware(),
        libNetHttp.RecoveryMiddleware(),
    )
    
    // Routes
    mux.HandleFunc("/health", handler(http.HandlerFunc(healthHandler)).ServeHTTP)
    mux.HandleFunc("/api/users", handler(http.HandlerFunc(usersHandler)).ServeHTTP)
    
    return mux
}

func healthHandler(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK)
    w.Write([]byte("OK"))
}

func usersHandler(w http.ResponseWriter, r *http.Request) {
    // Your user handling logic here
    response := map[string]string{"message": "Users endpoint"}
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(response)
}

This implementation provides full compatibility with requestCore while leveraging Go's standard net/http package for maximum performance and flexibility.

Documentation

Overview

Package libNetHttp provides a net/http web framework adapter for requestCore.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddSpanAttribute added in v0.18.0

func AddSpanAttribute(ctx context.Context, key, value string)

AddSpanAttribute adds an attribute to the current span

func AddSpanAttributes added in v0.18.0

func AddSpanAttributes(ctx context.Context, attrs map[string]string)

AddSpanAttributes adds multiple attributes to the current span

func AddSpanEvent added in v0.18.0

func AddSpanEvent(ctx context.Context, name string, attrs map[string]string)

AddSpanEvent adds an event to the current span

func CustomTracingMiddleware added in v0.18.0

func CustomTracingMiddleware(tm *libTracing.TracingManager) func(http.Handler) http.Handler

CustomTracingMiddleware creates a custom net/http middleware with more control

func GetSpanFromContext added in v0.18.0

func GetSpanFromContext(ctx context.Context) trace.Span

GetSpanFromContext gets the span from context

func NetHTTPErrorHandler added in v0.28.1

func NetHTTPErrorHandler(path, title string, handler ContextInitiator) http.HandlerFunc

NetHTTPErrorHandler returns an http.HandlerFunc that handles common HTTP errors for the given path.

func NetHTTPHandler added in v0.28.1

func NetHTTPHandler(handler any) http.HandlerFunc

NetHTTPHandler wraps a handler function to work with net/http

func RecordSpanError added in v0.18.0

func RecordSpanError(ctx context.Context, err error, attrs map[string]string)

RecordSpanError records an error in the current span

func RequestFromContext added in v0.23.0

func RequestFromContext(ctx context.Context) (*http.Request, bool)

RequestFromContext retrieves the HTTP request stored in the context.

func ResponseWriterFromContext added in v0.23.0

func ResponseWriterFromContext(ctx context.Context) (http.ResponseWriter, bool)

ResponseWriterFromContext retrieves the HTTP response writer stored in the context.

func TracingMiddleware added in v0.18.0

func TracingMiddleware() func(http.Handler) http.Handler

TracingMiddleware creates net/http middleware for OpenTelemetry tracing

func URLParamsFromRequest added in v0.23.0

func URLParamsFromRequest(r *http.Request) map[string]string

URLParamsFromRequest extracts URL parameters from the request context.

func WithRequestResponse added in v0.23.0

func WithRequestResponse(ctx context.Context, r *http.Request, w http.ResponseWriter) context.Context

WithRequestResponse stores the HTTP request and response writer in the context.

func WithURLParams added in v0.23.0

func WithURLParams(r *http.Request, params map[string]string) *http.Request

WithURLParams returns a new *http.Request with URL parameters stored in its context.

Types

type ContextInitiator

type ContextInitiator interface {
	InitContext(r *http.Request, w http.ResponseWriter) webFramework.WebFramework
	Respond(int, int, string, any, bool, webFramework.WebFramework)
}

ContextInitiator defines the interface for initializing a web framework context and responding.

type Middleware

type Middleware func(http.Handler) http.Handler

Middleware function type for net/http

func AuthMiddleware

func AuthMiddleware() Middleware

AuthMiddleware example for net/http

func CORSMiddleware

func CORSMiddleware() Middleware

CORSMiddleware returns a net/http middleware that sets CORS headers and handles preflight requests.

func ChainMiddleware

func ChainMiddleware(middlewares ...Middleware) Middleware

ChainMiddleware chains multiple middleware functions

func LoggingMiddleware

func LoggingMiddleware() Middleware

LoggingMiddleware returns a net/http middleware that logs each incoming request.

func RecoveryMiddleware

func RecoveryMiddleware() Middleware

RecoveryMiddleware returns a net/http middleware that recovers from panics.

type NetHTTPParser added in v0.28.1

type NetHTTPParser struct {
	Request  *http.Request
	Response http.ResponseWriter
	Locals   map[string]any
	Params   map[string]string
}

NetHTTPParser implements the webFramework.RequestParser interface for net/http.

func InitContext

func InitContext(r *http.Request, w http.ResponseWriter) *NetHTTPParser

InitContext creates a new NetHTTPParser from the given HTTP request and response writer.

func (NetHTTPParser) Abort added in v0.28.1

func (c NetHTTPParser) Abort() error

Abort stops the middleware chain by writing an internal-server-error status.

func (NetHTTPParser) AddCustomAttributes added in v0.28.1

func (c NetHTTPParser) AddCustomAttributes(attr slog.Attr)

AddCustomAttributes stores a custom slog attribute in the parser's local map.

func (*NetHTTPParser) AddParam added in v0.28.1

func (c *NetHTTPParser) AddParam(key, value string)

AddParam adds a single URL parameter

func (NetHTTPParser) AddSpanAttribute added in v0.28.1

func (c NetHTTPParser) AddSpanAttribute(key, value string)

AddSpanAttribute adds a single string attribute to the current tracing span.

func (NetHTTPParser) AddSpanAttributes added in v0.28.1

func (c NetHTTPParser) AddSpanAttributes(attrs map[string]string)

AddSpanAttributes adds multiple string attributes to the current tracing span.

func (NetHTTPParser) AddSpanEvent added in v0.28.1

func (c NetHTTPParser) AddSpanEvent(name string, attrs map[string]string)

AddSpanEvent adds an event with attributes to the current tracing span.

func (NetHTTPParser) CheckURLParam added in v0.28.1

func (c NetHTTPParser) CheckURLParam(name string) (string, bool)

CheckURLParam returns a URL path parameter by name and whether it exists.

func (NetHTTPParser) FileAttachment added in v0.28.1

func (c NetHTTPParser) FileAttachment(path, fileName string)

FileAttachment sends a file as an HTTP attachment with the given filename.

func (NetHTTPParser) FormValue added in v0.28.1

func (c NetHTTPParser) FormValue(name string) string

FormValue returns the first form value for the given field name.

func (NetHTTPParser) GetArgs added in v0.28.1

func (c NetHTTPParser) GetArgs(args ...any) map[string]string

GetArgs returns a map of common request arguments including user, app, action, and path.

func (NetHTTPParser) GetBody added in v0.28.1

func (c NetHTTPParser) GetBody(target any) error

GetBody reads and unmarshals the request body into the target.

func (NetHTTPParser) GetContext added in v0.28.1

func (c NetHTTPParser) GetContext() context.Context

GetContext returns the context from the HTTP request

func (NetHTTPParser) GetCookie added in v0.28.1

func (c NetHTTPParser) GetCookie(name string) (*http.Cookie, error)

GetCookie gets a cookie by name

func (NetHTTPParser) GetCookies added in v0.28.1

func (c NetHTTPParser) GetCookies() []*http.Cookie

GetCookies gets all cookies

func (NetHTTPParser) GetFormValue added in v0.28.1

func (c NetHTTPParser) GetFormValue(key string) string

GetFormValue gets form value

func (NetHTTPParser) GetFormValues added in v0.28.1

func (c NetHTTPParser) GetFormValues(key string) []string

GetFormValues gets all form values for a key

func (NetHTTPParser) GetHTTPHeader added in v0.28.1

func (c NetHTTPParser) GetHTTPHeader() http.Header

GetHTTPHeader returns the full HTTP header map from the request.

func (NetHTTPParser) GetHeader added in v0.28.1

func (c NetHTTPParser) GetHeader(target webFramework.HeaderInterface) error

GetHeader populates the target struct with header values from the request.

func (NetHTTPParser) GetHeaderValue added in v0.28.1

func (c NetHTTPParser) GetHeaderValue(name string) string

GetHeaderValue returns the value of a single request header by name.

func (NetHTTPParser) GetLocal added in v0.28.1

func (c NetHTTPParser) GetLocal(name string) any

GetLocal returns a value stored in the parser's local map by name.

func (NetHTTPParser) GetLocalString added in v0.28.1

func (c NetHTTPParser) GetLocalString(name string) string

GetLocalString returns a string value stored in the parser's local map by name.

func (NetHTTPParser) GetMethod added in v0.28.1

func (c NetHTTPParser) GetMethod() string

GetMethod returns the HTTP method of the request.

func (NetHTTPParser) GetPath added in v0.28.1

func (c NetHTTPParser) GetPath() string

GetPath returns the URL path of the request.

func (NetHTTPParser) GetPostFormValue added in v0.28.1

func (c NetHTTPParser) GetPostFormValue(key string) string

GetPostFormValue gets POST form value

func (NetHTTPParser) GetPostFormValues added in v0.28.1

func (c NetHTTPParser) GetPostFormValues(key string) []string

GetPostFormValues gets all POST form values for a key

func (NetHTTPParser) GetRawURLQuery added in v0.28.1

func (c NetHTTPParser) GetRawURLQuery() string

GetRawURLQuery returns the raw query string from the request URL.

func (NetHTTPParser) GetTraceContext added in v0.28.1

func (c NetHTTPParser) GetTraceContext() trace.SpanContext

GetTraceContext returns the trace span context from the net/http request context.

func (NetHTTPParser) GetURI added in v0.28.1

func (c NetHTTPParser) GetURI(target any) error

GetURI parses URL path parameters into the target struct.

func (NetHTTPParser) GetURLParam added in v0.28.1

func (c NetHTTPParser) GetURLParam(name string) string

GetURLParam returns a single URL path parameter by name.

func (NetHTTPParser) GetURLParams added in v0.28.1

func (c NetHTTPParser) GetURLParams() map[string]string

GetURLParams returns all URL path parameters as a map.

func (NetHTTPParser) GetURLQuery added in v0.28.1

func (c NetHTTPParser) GetURLQuery(target any) error

GetURLQuery parses URL query parameters into the target struct.

func (NetHTTPParser) Next added in v0.28.1

func (c NetHTTPParser) Next() error

Next advances to the next middleware in the chain (no-op for net/http).

func (NetHTTPParser) ParseCommand added in v0.28.1

func (c NetHTTPParser) ParseCommand(command, title string, request webFramework.RecordData, parser webFramework.FieldParser) string

ParseCommand parses a DML command template using local values and the provided request data.

func (NetHTTPParser) ParseForm added in v0.28.1

func (c NetHTTPParser) ParseForm() error

ParseForm parses form data

func (NetHTTPParser) ParseMultipartForm added in v0.28.1

func (c NetHTTPParser) ParseMultipartForm(maxMemory int64) error

ParseMultipartForm parses multipart form data ParseMultipartForm parses multipart form data from the request with the given max memory.

func (NetHTTPParser) RecordSpanError added in v0.28.1

func (c NetHTTPParser) RecordSpanError(err error, attrs map[string]string)

RecordSpanError records an error with attributes on the current tracing span.

func (NetHTTPParser) Redirect added in v0.28.1

func (c NetHTTPParser) Redirect(url string, statusCode int)

Redirect redirects to a URL

func (NetHTTPParser) SaveFile added in v0.28.1

func (c NetHTTPParser) SaveFile(formTagName, path string) error

SaveFile saves an uploaded file from the given form tag to the specified path.

func (NetHTTPParser) SendJSONRespBody added in v0.28.1

func (c NetHTTPParser) SendJSONRespBody(status int, resp any) error

SendJSONRespBody writes a JSON response with the given HTTP status code.

func (NetHTTPParser) ServeContent added in v0.28.1

func (c NetHTTPParser) ServeContent(name string, modtime time.Time, content io.ReadSeeker)

ServeContent serves content

func (NetHTTPParser) ServeFile added in v0.28.1

func (c NetHTTPParser) ServeFile(name string)

ServeFile serves a file

func (*NetHTTPParser) SetContext added in v0.28.1

func (c *NetHTTPParser) SetContext(ctx context.Context)

SetContext updates the context in the HTTP request. It uses a pointer receiver because http.Request.WithContext returns a new *http.Request and the mutation must be visible to callers.

func (NetHTTPParser) SetCookie added in v0.28.1

func (c NetHTTPParser) SetCookie(cookie *http.Cookie)

SetCookie sets a cookie

func (NetHTTPParser) SetLocal added in v0.28.1

func (c NetHTTPParser) SetLocal(name string, value any)

SetLocal stores a value in the parser's local map by name.

func (*NetHTTPParser) SetParams added in v0.28.1

func (c *NetHTTPParser) SetParams(params map[string]string)

SetParams sets URL parameters (useful for routing)

func (NetHTTPParser) SetReqHeader added in v0.28.1

func (c NetHTTPParser) SetReqHeader(name string, value string)

SetReqHeader sets a request header value by name.

func (NetHTTPParser) SetRespHeader added in v0.28.1

func (c NetHTTPParser) SetRespHeader(name string, value string)

SetRespHeader sets a response header value by name.

func (NetHTTPParser) SetTraceContext added in v0.28.1

func (c NetHTTPParser) SetTraceContext(_ trace.SpanContext)

SetTraceContext sets the trace span context on the request (no-op for net/http).

func (NetHTTPParser) StartSpan added in v0.28.1

StartSpan starts a new tracing span from the request context.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL