Home > Article > Backend Development > How to build your own golang framework from scratch?
How to build a Go framework from scratch: Initialize the project: Create a Go module and set up the basic project structure. Create the necessary packages: Create two packages to handle requests and provide middleware. Define a basic Handler: Define a Handler interface containing the ServeHTTP method. Create Middleware: Define a Middleware interface containing the HandlerWrapper method. Create specific Handlers and Middleware: Create HelloHandler and LoggingMiddleware. Create an HTTP router: Use the Gorilla mux router to handle requests. Main function: Create a router and register HelloHandler.
In this article, we will guide you step by step on how to build your own Go framework from scratch. It is crucial to master the basics of the Go framework so that you can customize the framework to your specific requirements.
First, create a Go module and initialize a basic project structure.
mkdir my-framework cd my-framework go mod init my-framework
For a basic framework, let’s create two packages: one for handling requests, the handler
package, and another for middleware
package that provides middleware.
mkdir -p handler middleware
In handler/handler.go
, define a Handler
interface, which contains a ServeHTTP
method.
package handler import ( "net/http" ) // Handler defines an interface for handling HTTP requests. type Handler interface { ServeHTTP(w http.ResponseWriter, r *http.Request) }
In middleware/middleware.go
, define a Middleware
interface, which contains a HandlerWrapper
method. Middleware wraps the Handler into a new Handler.
package middleware import "github.com/my-framework/handler" // Middleware defines an interface for wrapping request handlers. type Middleware interface { HandlerWrapper(handler handler.Handler) handler.Handler }
Now, let us create a simple HelloHandler
and a LoggingMiddleware
.
handler/hello.go:
package handler import ( "net/http" ) // HelloHandler implements the Handler interface. type HelloHandler struct{} // ServeHTTP writes "Hello, world!" to the response. func (h HelloHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello, world!")) }
middleware/logging.go:
package middleware import ( "github.com/my-framework/handler" "log" "time" ) // LoggingMiddleware logs the request method and URI. type LoggingMiddleware struct{} // HandlerWrapper returns a new Handler that logs requests. func (m LoggingMiddleware) HandlerWrapper(handler handler.Handler) handler.Handler { return handler.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { log.Printf("%s %s", r.Method, r.RequestURI) handler.ServeHTTP(w, r) }) }
Now, let's create a simple HTTP router to handle requests.
router/router.go:
package router import ( "github.com/gorilla/mux" "github.com/my-framework/handler" "github.com/my-framework/middleware" ) // Router handles HTTP requests using a Gorilla mux router. type Router struct { mux *mux.Router middlewares []middleware.Middleware } // NewRouter initializes a new HTTP router. func NewRouter() *Router { return &Router{ mux: mux.NewRouter(), middlewares: []middleware.Middleware{}, } } // Use adds a middleware to the router. func (r *Router) Use(m middleware.Middleware) { r.middlewares = append(r.middlewares, m) } // Handle registers a route with a handler. func (r *Router) Handle(path string, handler handler.Handler) { r.mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) { for _, m := range r.middlewares { handler = m.HandlerWrapper(handler) } handler.ServeHTTP(w, r) }) } // ServeHTTP serves HTTP requests. func (r *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) { r.mux.ServeHTTP(w, r) }
Finally, in main.go
, create A router and register our HelloHandler.
package main import ( "fmt" "net/http" "time" "github.com/my-framework/middleware" "github.com/my-framework/handler" "github.com/my-framework/router" ) func main() { r := router.NewRouter() r.Use(middleware.LoggingMiddleware{}) r.Handle("/", handler.HelloHandler{}) server := &http.Server{ Addr: ":8080", Handler: r, ReadTimeout: 5 * time.Second, WriteTimeout: 5 * time.Second, } fmt.Println("Listening on port 8080") server.ListenAndServe() }
Now you can run your framework:
go run main.go
Visit http://localhost:8080
, you should see "Hello, world!".
congratulations! You have now created your own basic Go framework. You can extend it further by adding more Handlers, Middleware, and custom functionality.
The above is the detailed content of How to build your own golang framework from scratch?. For more information, please follow other related articles on the PHP Chinese website!