httpsrv

package module
v0.12.7 Latest Latest
Warning

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

Go to latest
Published: Mar 1, 2026 License: Apache-2.0 Imports: 24 Imported by: 41

README

httpsrv

httpsrv is a lightweight, modular, high-performance MVC web framework designed for Go, suitable for developing various internet-facing APIs and web applications.

Language: English | 中文

Features

  • Modular Architecture - Business code organized through modules, ideal for enterprise-level complex application development
  • Lightweight & Concise - Core code is concise (~3000 lines) with stable and reliable interfaces, easy for long-term maintenance
  • High Performance - Low memory footprint, high concurrency stability, QPS can reach 20000+ on 2-core instances from mainstream cloud providers
  • MVC Pattern - Supports standard MVC architecture with clear code structure
  • Template Engine - Built-in template engine supporting flexible view rendering
  • Internationalization - Built-in i18n support for multiple languages
  • Middleware - Supports request filters and interceptors
  • Session Management - Built-in session management functionality

Documentation

Installation

go get -u github.com/hooto/httpsrv

Quick Start

Create a simple Hello World application:

package main

import (
    "github.com/hooto/httpsrv"
)

// Define a controller
type Hello struct {
    *httpsrv.Controller
}

// Define an Action
func (c Hello) WorldAction() {
    c.RenderString("hello world")
}

// Create module
func NewModule() httpsrv.Module {
    module := httpsrv.NewModule("demo")
    module.ControllerRegister(new(Hello))
    return module
}

func main() {
    // Register module to global service
    httpsrv.GlobalService.ModuleRegister("/", NewModule())
    
    // Set port
    httpsrv.GlobalService.Config.HttpPort = 8080
    
    // Start service
    httpsrv.GlobalService.Start()
}

Run:

go run main.go

Visit:

curl http://localhost:8080/hello/world/

Output:

hello world

Project Structure

Recommended directory structure:

├─ bin/              # Compiled executables
├─ etc/              # Configuration files
├─ config/           # Configuration parsing code
├─ cmd/
│  └─ server/
│     └─ main.go     # Service entry point
├─ data/             # Database access layer
├─ websrv/           # Module directory
│  ├─ api-v1/        # API module
│  └─ frontend/      # Frontend module
│     └─ views/      # Template files
├─ webui/            # Static files
└─ var/              # Runtime data

Complete example project: httpsrv-demo

httpsrv keeps the core concise. Here are some recommended third-party libraries:

Database
Utility Libraries

More Go ecosystem libraries: awesome-go

System Requirements

  • Go Version: 1.22 or higher
  • Recommended Systems: Linux, Unix, or macOS (Windows not tested for compatibility)

Core Components

  • Service - Service container and configuration management
  • Config - Configuration file handling
  • Module - Module management and routing
  • Controller - Controller and request handling
  • Template - Template rendering and views
  • Router - Routing configuration and matching

Extension Components

  • log - Logging extension
  • data-rdb - Relational database extension
  • data-kv - Key-Value database extension
  • flag - Command line argument extension

Reference Projects

httpsrv has referenced the following projects in architecture design and some code implementations. Special thanks!

License

Apache License 2.0

Documentation

Index

Constants

View Source
const Version = "0.12.0"

Variables

View Source
var (
	DefaultModule = &Module{
		idxHandlers: make(map[string]*regHandler),
		routes:      make(map[string]*regRouter),
	}

	DefaultModules = []*Module{}
)
View Source
var DefaultConfig = Config{

	HttpAddr: "0.0.0.0",
	HttpPort: 8080,

	HttpTimeout: 30,

	CookieKeyLocale:  "lang",
	CookieKeySession: "access_token",
}
View Source
var DefaultFilters = []Filter{
	ParamsFilter,
	SessionFilter,
	I18nFilter,
}

Filters is the default set of global filters. It may be set by the application on initialization.

View Source
var (
	DefaultService = NewService()
)
View Source
var TemplateFuncs = map[string]interface{}{

	"raw": func(text string) template.HTML {
		return template.HTML(text)
	},

	"replace": func(s, old, new string) string {
		return strings.Replace(s, old, new, -1)
	},

	"date": func(t time.Time) string {
		return t.Format("2006-01-02")
	},
	"datetime": func(t time.Time) string {

		return t.Format("2006-01-02 15:04")
	},

	"upper": func(s string) string {
		return strings.ToUpper(s)
	},

	"lower": func(s string) string {
		return strings.ToLower(s)
	},

	"T": func(lang map[string]interface{}, msg string, args ...interface{}) string {
		if lang == nil {
			return i18nTranslate(i18nDefLocale, msg, args...)
		}
		if v, ok := lang["LANG"]; ok {
			if langStr, ok := v.(string); ok && langStr != "" {
				return i18nTranslate(langStr, msg, args...)
			}
		}
		return i18nTranslate(i18nDefLocale, msg, args...)
	},
}

Functions

func I18nFilter

func I18nFilter(c *Controller)

func ParamsFilter

func ParamsFilter(c *Controller)

func SessionFilter

func SessionFilter(c *Controller)

Types

type Config

type Config struct {
	// e.g. "127.0.0.1", "unix:/tmp/app.sock"
	HttpAddr string `json:"http_addr,omitempty" toml:"http_addr,omitempty"`

	// e.g. 8080
	HttpPort uint16 `json:"http_port,omitempty" toml:"http_port,omitempty"`

	HttpTimeout uint16 `json:"http_timeout,omitempty" toml:"http_timeout,omitempty"`

	UrlBasePath string `json:"url_base_path,omitempty" toml:"url_base_path,omitempty"`

	CookieKeyLocale  string `json:"cookie_key_locale,omitempty" toml:"cookie_key_locale,omitempty"`
	CookieKeySession string `json:"cookie_key_session,omitempty" toml:"cookie_key_session,omitempty"`

	CompressResponse bool `json:"compress_response,omitempty" toml:"compress_response,omitempty"`
}

func (*Config) I18n

func (c *Config) I18n(file string)

func (*Config) RegisterTemplateFunc added in v0.12.2

func (c *Config) RegisterTemplateFunc(name string, fn interface{})

type Controller

type Controller struct {
	Name       string // The controller name, e.g. "App"
	ActionName string // The action name, e.g. "Index"
	Request    *Request
	Response   *Response
	Params     *Params  // Parameters from URL and form (including multipart).
	Session    *Session // Session, stored in cookie, signed.
	AutoRender bool
	Data       map[string]interface{}
	// contains filtered or unexported fields
}

func (*Controller) Redirect

func (c *Controller) Redirect(url string)

func (*Controller) Render

func (c *Controller) Render(args ...interface{})

func (*Controller) RenderError

func (c *Controller) RenderError(status int, msg string)

func (*Controller) RenderHTML added in v0.12.5

func (c *Controller) RenderHTML(htm string)

func (*Controller) RenderJson

func (c *Controller) RenderJson(obj interface{})

func (*Controller) RenderJsonIndent

func (c *Controller) RenderJsonIndent(obj interface{}, indent string)

func (*Controller) RenderString

func (c *Controller) RenderString(v string)

func (*Controller) Translate

func (c *Controller) Translate(msg string, args ...interface{}) string

func (*Controller) UrlBase

func (c *Controller) UrlBase(path string) string

func (*Controller) UrlModuleBase

func (c *Controller) UrlModuleBase(path string) string

type Filter

type Filter func(c *Controller)

type Module

type Module struct {
	Path string
	// contains filtered or unexported fields
}

func NewModule

func NewModule() *Module

func (*Module) RegisterController added in v0.12.0

func (m *Module) RegisterController(args ...interface{})

func (*Module) RegisterFileServer added in v0.12.2

func (m *Module) RegisterFileServer(pattern, path string, fs http.FileSystem)

func (*Module) SetRoute added in v0.12.1

func (m *Module) SetRoute(pattern string, params map[string]string)

func (*Module) SetTemplateFileSystem added in v0.12.0

func (m *Module) SetTemplateFileSystem(fss ...http.FileSystem)

func (*Module) SetTemplatePath added in v0.12.0

func (m *Module) SetTemplatePath(paths ...string)

type Params

type Params struct {
	// contains filtered or unexported fields
}

func (*Params) FloatValue added in v0.12.2

func (p *Params) FloatValue(key string) float64

func (*Params) IntValue added in v0.12.2

func (p *Params) IntValue(key string) int64

func (*Params) SetValue added in v0.12.1

func (p *Params) SetValue(key, value string)

func (*Params) Value added in v0.12.2

func (p *Params) Value(key string) string

type Request

type Request struct {
	*http.Request
	Time        time.Time
	ContentType string

	Locale string
	// contains filtered or unexported fields
}

func (*Request) JsonDecode

func (req *Request) JsonDecode(obj interface{}) error

func (*Request) RawAbsUrl

func (req *Request) RawAbsUrl() string

func (*Request) RawBody

func (req *Request) RawBody() []byte

func (*Request) UrlPath added in v0.12.1

func (req *Request) UrlPath() string

func (*Request) UrlRoutePath added in v0.12.1

func (req *Request) UrlRoutePath() string

type Response

type Response struct {
	Status int
	Out    http.ResponseWriter
	// contains filtered or unexported fields
}

func (*Response) Header added in v0.11.0

func (resp *Response) Header() http.Header

func (*Response) Write added in v0.11.0

func (resp *Response) Write(b []byte) (int, error)

func (*Response) WriteHeader

func (resp *Response) WriteHeader(status int)

type Service

type Service struct {
	Config  Config
	Filters []Filter

	TemplateLoader *TemplateLoader
	// contains filtered or unexported fields
}

func NewService

func NewService() *Service

func (*Service) HandleFunc added in v0.12.0

func (s *Service) HandleFunc(pattern string, h func(w http.ResponseWriter, r *http.Request))

func (*Service) HandleModule added in v0.12.0

func (s *Service) HandleModule(pattern string, mod *Module)

func (*Service) Start

func (s *Service) Start(args ...interface{}) error

func (*Service) Stop

func (s *Service) Stop() error

type Session

type Session struct {
	// contains filtered or unexported fields
}

func (*Session) AuthToken

func (s *Session) AuthToken(key string) string

func (*Session) Value added in v0.12.2

func (s *Session) Value(key string) string

type TemplateLoader

type TemplateLoader struct {
	// contains filtered or unexported fields
}

This object handles loading and parsing of templates. Everything below the application's views directory is treated as a template.

func (*TemplateLoader) Clean

func (it *TemplateLoader) Clean(modUrlBase string)

func (*TemplateLoader) Render

func (it *TemplateLoader) Render(wr io.Writer, modUrlBase, tplPath string, arg interface{}) error

func (*TemplateLoader) Set

func (it *TemplateLoader) Set(modUrlBase string, viewpaths []string, viewfss []http.FileSystem)

Directories

Path Synopsis
internal
lru
Package lru implements an LRU cache.
Package lru implements an LRU cache.

Jump to

Keyboard shortcuts

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