/**
* example.go
*
* @link https://cnblogs.com/farwish
*/
package main import "github.com/gin-gonic/gin" func main() {
   // 由于是外部调用包,所以必须含包名 gin. 作为前缀
   // Default 返回带有已连接 Logger 和 Recovery 中间件的 Engine 实例。
r := gin.Default()

   // Engine 结构体中内嵌了 RouterGroup 结构体,即继承了 RouterGroup(其有成员方法 GET、POST、DELETE、PUT、ANY 等)
r.GET("/ping", func(c *gin.Context) {

     // 使用 context.go 提供的方法渲染 json
     // 关于 gin.H 可看这里:https://www.cnblogs.com/farwish/p/12628549.html
c.JSON(200, gin.H{
"message": "pong",
})

})

  // 默认是 0.0.0.0:8080 端口,内部使用了 http.ListenAndServe(address, engine)
r.Run("9090") // listen and serve on 0.0.0.0:9090
}

https://sourcegraph.com/github.com/gin-gonic/gin/-/blob/gin.go
// gin.go

// Default returns an Engine instance with the Logger and Recovery middleware already attached.
func Default() *Engine {
  // 打印 WARNING 信息,见 debug.go
debugPrintWARNINGDefault()

  // 取得一个新的空 Engine 实例
engine := New()

  // 添加路由的全局中间件
engine.Use(Logger(), Recovery())

return engine
} // Engine is the framework's instance, it contains the muxer, middleware and configuration settings.
// Create an instance of Engine, by using New() or Default()
type Engine struct {
RouterGroup // Enables automatic redirection if the current route can't be matched but a
// handler for the path with (without) the trailing slash exists.
// For example if /foo/ is requested but a route only exists for /foo, the
// client is redirected to /foo with http status code 301 for GET requests
// and 307 for all other request methods.
RedirectTrailingSlash bool // If enabled, the router tries to fix the current request path, if no
// handle is registered for it.
// First superfluous path elements like ../ or // are removed.
// Afterwards the router does a case-insensitive lookup of the cleaned path.
// If a handle can be found for this route, the router makes a redirection
// to the corrected path with status code 301 for GET requests and 307 for
// all other request methods.
// For example /FOO and /..//Foo could be redirected to /foo.
// RedirectTrailingSlash is independent of this option.
RedirectFixedPath bool // If enabled, the router checks if another method is allowed for the
// current route, if the current request can not be routed.
// If this is the case, the request is answered with 'Method Not Allowed'
// and HTTP status code 405.
// If no other Method is allowed, the request is delegated to the NotFound
// handler.
HandleMethodNotAllowed bool
ForwardedByClientIP bool // #726 #755 If enabled, it will thrust some headers starting with
// 'X-AppEngine...' for better integration with that PaaS.
AppEngine bool // If enabled, the url.RawPath will be used to find parameters.
UseRawPath bool // If true, the path value will be unescaped.
// If UseRawPath is false (by default), the UnescapePathValues effectively is true,
// as url.Path gonna be used, which is already unescaped.
UnescapePathValues bool // Value of 'maxMemory' param that is given to http.Request's ParseMultipartForm
// method call.
MaxMultipartMemory int64 // RemoveExtraSlash a parameter can be parsed from the URL even with extra slashes.
// See the PR #1817 and issue #1644
RemoveExtraSlash bool delims render.Delims
secureJsonPrefix string
HTMLRender render.HTMLRender
FuncMap template.FuncMap
allNoRoute HandlersChain
allNoMethod HandlersChain
noRoute HandlersChain
noMethod HandlersChain
pool sync.Pool
trees methodTrees
} // New returns a new blank Engine instance without any middleware attached.
// By default the configuration is:
// - RedirectTrailingSlash: true
// - RedirectFixedPath: false
// - HandleMethodNotAllowed: false
// - ForwardedByClientIP: true
// - UseRawPath: false
// - UnescapePathValues: true
func New() *Engine {
debugPrintWARNINGNew()
engine := &Engine{
RouterGroup: RouterGroup{
Handlers: nil,
basePath: "/",
root: true,
},
FuncMap: template.FuncMap{},
RedirectTrailingSlash: true,
RedirectFixedPath: false,
HandleMethodNotAllowed: false,
ForwardedByClientIP: true,
AppEngine: defaultAppEngine,
UseRawPath: false,
RemoveExtraSlash: false,
UnescapePathValues: true,
MaxMultipartMemory: defaultMultipartMemory,
trees: make(methodTrees, 0, 9),
delims: render.Delims{Left: "{{", Right: "}}"},
secureJsonPrefix: "while(1);",
}
engine.RouterGroup.engine = engine
engine.pool.New = func() interface{} {
return engine.allocateContext()
}
return engine
}

func (engine *Engine) addRoute(method, path string, handlers HandlersChain) {
assert1(path[0] == '/', "path must begin with '/'")
assert1(method != "", "HTTP method can not be empty")
assert1(len(handlers) > 0, "there must be at least one handler") debugPrintRoute(method, path, handlers)
root := engine.trees.get(method)
if root == nil {
root = new(node)
root.fullPath = "/"
engine.trees = append(engine.trees, methodTree{method: method, root: root})
}
root.addRoute(path, handlers)
}

// Run attaches the router to a http.Server and starts listening and serving HTTP requests.
// It is a shortcut for http.ListenAndServe(addr, router)
// Note: this method will block the calling goroutine indefinitely unless an error happens.
func (engine *Engine) Run(addr ...string) (err error) {
defer func() { debugPrintError(err) }() address := resolveAddress(addr)
debugPrint("Listening and serving HTTP on %s\n", address)
err = http.ListenAndServe(address, engine)
return
}

// Use attaches a global middleware to the router. ie. the middleware attached though Use() will be
// included in the handlers chain for every single request. Even 404, 405, static files...
// For example, this is the right place for a logger or error management middleware.
func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes {
engine.RouterGroup.Use(middleware...)
engine.rebuild404Handlers()
engine.rebuild405Handlers()
return engine
}

https://sourcegraph.com/github.com/gin-gonic/gin/-/blob/routergroup.go

// routergroup.go

// Use adds middleware to the group, see example code in GitHub.
func (group *RouterGroup) Use(middleware ...HandlerFunc) IRoutes {
group.Handlers = append(group.Handlers, middleware...)
return group.returnObj()
} // Group creates a new router group. You should add all the routes that have common middlewares or the same path prefix.
// For example, all the routes that use a common middleware for authorization could be grouped.
func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup {
return &RouterGroup{
Handlers: group.combineHandlers(handlers),
basePath: group.calculateAbsolutePath(relativePath),
engine: group.engine,
}
} // BasePath returns the base path of router group.
// For example, if v := router.Group("/rest/n/v1/api"), v.BasePath() is "/rest/n/v1/api".
func (group *RouterGroup) BasePath() string {
return group.basePath
} func (group *RouterGroup) handle(httpMethod, relativePath string, handlers HandlersChain) IRoutes {
absolutePath := group.calculateAbsolutePath(relativePath)
handlers = group.combineHandlers(handlers)
group.engine.addRoute(httpMethod, absolutePath, handlers)
return group.returnObj()
} func (group *RouterGroup) combineHandlers(handlers HandlersChain) HandlersChain {
finalSize := len(group.Handlers) + len(handlers)
if finalSize >= int(abortIndex) {
panic("too many handlers")
}
mergedHandlers := make(HandlersChain, finalSize)
copy(mergedHandlers, group.Handlers)
copy(mergedHandlers[len(group.Handlers):], handlers)
return mergedHandlers
} func (group *RouterGroup) calculateAbsolutePath(relativePath string) string {
return joinPaths(group.basePath, relativePath)
} func (group *RouterGroup) returnObj() IRoutes {
if group.root {
return group.engine
}
return group
} // Handle registers a new request handle and middleware with the given path and method.
// The last handler should be the real handler, the other ones should be middleware that can and should be shared among different routes.
// See the example code in GitHub.
//
// For GET, POST, PUT, PATCH and DELETE requests the respective shortcut
// functions can be used.
//
// This function is intended for bulk loading and to allow the usage of less
// frequently used, non-standardized or custom methods (e.g. for internal
// communication with a proxy).
func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) IRoutes {
if matches, err := regexp.MatchString("^[A-Z]+$", httpMethod); !matches || err != nil {
panic("http method " + httpMethod + " is not valid")
}
return group.handle(httpMethod, relativePath, handlers)
}

https://sourcegraph.com/github.com/gin-gonic/gin/-/blob/context.go

// context.go

// JSON serializes the given struct as JSON into the response body.
// It also sets the Content-Type as "application/json".
func (c *Context) JSON(code int, obj interface{}) {
  // render.JSON 见 github.com/gin-gonic/gin/render
c.Render(code, render.JSON{Data: obj})
} // Render writes the response headers and calls render.Render to render data.
func (c *Context) Render(code int, r render.Render) {
c.Status(code) if !bodyAllowedForStatus(code) {
r.WriteContentType(c.Writer)
c.Writer.WriteHeaderNow()
return
} if err := r.Render(c.Writer); err != nil {
panic(err)
}
}

https://sourcegraph.com/github.com/gin-gonic/gin/-/blob/render/render.go

// render/render.go

package render

import "net/http"

// Render interface is to be implemented by JSON, XML, HTML, YAML and so on.
type Render interface {
// Render writes data with custom ContentType.
Render(http.ResponseWriter) error
// WriteContentType writes custom ContentType.
WriteContentType(w http.ResponseWriter)
} var (
_ Render = JSON{}
_ Render = IndentedJSON{}
_ Render = SecureJSON{}
_ Render = JsonpJSON{}
_ Render = XML{}
_ Render = String{}
_ Render = Redirect{}
_ Render = Data{}
_ Render = HTML{}
_ HTMLRender = HTMLDebug{}
_ HTMLRender = HTMLProduction{}
_ Render = YAML{}
_ Render = Reader{}
_ Render = AsciiJSON{}
_ Render = ProtoBuf{}
) func writeContentType(w http.ResponseWriter, value []string) {
header := w.Header()
if val := header["Content-Type"]; len(val) == 0 {
header["Content-Type"] = value
}
}

https://sourcegraph.com/github.com/gin-gonic/gin/-/blob/render/json.go

// rendor/json.go

// JSON contains the given interface object.
type JSON struct {
Data interface{}
} var jsonContentType = []string{"application/json; charset=utf-8"}
var jsonpContentType = []string{"application/javascript; charset=utf-8"}
var jsonAsciiContentType = []string{"application/json"} // Render (JSON) writes data with custom ContentType.
func (r JSON) Render(w http.ResponseWriter) (err error) {
if err = WriteJSON(w, r.Data); err != nil {
panic(err)
}
return
} // WriteContentType (JSON) writes JSON ContentType.
func (r JSON) WriteContentType(w http.ResponseWriter) {
writeContentType(w, jsonContentType)
} // WriteJSON marshals the given interface object and writes it with custom ContentType.
func WriteJSON(w http.ResponseWriter, obj interface{}) error {
writeContentType(w, jsonContentType)
jsonBytes, err := json.Marshal(obj)
if err != nil {
return err
}
_, err = w.Write(jsonBytes)
return err
}

https://sourcegraph.com/github.com/gin-gonic/gin/-/blob/debug.go

// debug.go

func debugPrintWARNINGDefault() {
if v, e := getMinVer(runtime.Version()); e == nil && v <= ginSupportMinGoVer {
debugPrint(`[WARNING] Now Gin requires Go 1.11 or later and Go 1.12 will be required soon. `)
}
debugPrint(`[WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached. `)
} func debugPrintWARNINGNew() {
debugPrint(`[WARNING] Running in "debug" mode. Switch to "release" mode in production.
- using env: export GIN_MODE=release
- using code: gin.SetMode(gin.ReleaseMode) `)
} func debugPrint(format string, values ...interface{}) {
if IsDebugging() {
if !strings.HasSuffix(format, "\n") {
format += "\n"
}
fmt.Fprintf(DefaultWriter, "[GIN-debug] "+format, values...)
}
} // IsDebugging returns true if the framework is running in debug mode.
// Use SetMode(gin.ReleaseMode) to disable debug mode.
func IsDebugging() bool {
return ginMode == debugCode
}

Refer:Golang Http Server
Link: https://www.cnblogs.com/farwish/p/12701654.html

[Gin] 单文件极简 HTTP Server 流程分析 ( gin-gonic/gin )的更多相关文章

  1. 1分钟搭建极简mock server

    1.无聊的背景.起源: 如今的业务系统越来越复杂庞大,各个功能直接的调用也是多如牛毛,但如果在联调的时候,恰好被调的接口正在开发,怎么办?傻傻的等么,不存在的!这时会搭建一些server来进行mock ...

  2. ubuntu为什么没有/etc/inittab文件? 深究ubuntu的启动流程分析

    Linux 内核启动 init ,init进程ID是1,是所有进程的父进程,所有进程由它控制. Ubuntu 的启动由upstart控制,自9.10后不再使用/etc/event.d目录的配置文件,改 ...

  3. TS文件极简合并

    TS文件是可以直接通过二进制拷贝连接的方式进行合并的,一般采用如下的命令行参数:copy /b 1.ts+2.ts+3.ts new.ts 这个例子就是将1.ts.2.ts.3.ts三个文件按顺序连接 ...

  4. Spring 文件上传MultipartFile 执行流程分析

    在了解Spring 文件上传执行流程之前,我们必须知道两点: 1.Spring 文件上传是基于common-fileUpload 组件的,所以,文件上传必须引入此包 2.Spring 文件上传需要在X ...

  5. 在Web应用中接入微信支付的流程之极简清晰版

    在Web应用中接入微信支付的流程之极简清晰版 背景: 在Web应用中接入微信支付,我以为只是调用几个API稍作调试即可. 没想到微信的API和官方文档里隐坑无数,致我抱着怀疑人生的心情悲愤踩遍了丫们布 ...

  6. 在Web应用中接入微信支付的流程之极简清晰版 (转)

    在Web应用中接入微信支付的流程之极简清晰版 背景: 在Web应用中接入微信支付,我以为只是调用几个API稍作调试即可. 没想到微信的API和官方文档里隐坑无数,致我抱着怀疑人生的心情悲愤踩遍了丫们布 ...

  7. 一款极简的流媒体Web服务器(Streaming Media Web Server),提供视频音乐的在线播放功能

    一款极简的流媒体Web服务器(Streaming Media Web Server),提供视频音乐的在线播放功能 A extremely simple web server of streaming ...

  8. 极简 Node.js 入门 - 3.2 文件读取

    极简 Node.js 入门系列教程:https://www.yuque.com/sunluyong/node 本文更佳阅读体验:https://www.yuque.com/sunluyong/node ...

  9. 极简 Node.js 入门 - 3.3 文件写入

    极简 Node.js 入门系列教程:https://www.yuque.com/sunluyong/node 本文更佳阅读体验:https://www.yuque.com/sunluyong/node ...

  10. 极简 Node.js 入门 - 3.4 文件夹写入

    极简 Node.js 入门系列教程:https://www.yuque.com/sunluyong/node 本文更佳阅读体验:https://www.yuque.com/sunluyong/node ...

随机推荐

  1. CYQ.Data 操作 Json 性能测试:对比 Newtonsoft.Json

    前言: 在 CYQ.Data 版本更新的这么多年,中间过程的版本都在完善各种功能. 基于需要支持或兼容的代码越多,很多时候,常规思维,都把相关功能完成,就结束了. 实现过程中,无法避免的会用到大量的反 ...

  2. html+css实现指针时钟

    周末时间,突然想用html+css实现一个简单的指针时钟的功能,以下是具体代码实现,文末附有线上链接地址. 效果图: 1.代码 1.1.clock.html <!DOCTYPE html> ...

  3. C++获取任务管理器信息,封装成DLL,C#调用例子

    C++代码 pch.h // pch.h: 这是预编译标头文件. // 下方列出的文件仅编译一次,提高了将来生成的生成性能. // 这还将影响 IntelliSense 性能,包括代码完成和许多代码浏 ...

  4. KingbaseES V8R3集群部署案例之---通用机无ssh环境脚本部署集群

    案例说明: 在一些通用机的生产环境,不允许主机之间通过ssh通讯,或者不允许root用户建立ssh互信或登录.默认KingbaseES V8R3集群通用机环境部署需要建立数据库用户及root用户,在集 ...

  5. 算法学习笔记【1】| LCA(最近公共祖先)

    LCA(最近公共祖先) Part 1:逐步上跳 假设u,v是所求的两点,先把深度大的点逐步上移直到深度相同. 然后两者同时上移,直到第一次遇到相同的点为止. 时间复杂度: O(n)<script ...

  6. #三分,分治,计算几何,prim#JZOJ 3860 地壳运动

    题目 \(q\)组询问查询最小生成树,边权为\(u*k1+v*k2\)(\(k1,k2\)每次询问都不同) \(n\leq 35,m\leq 25000,q\leq 200000\) 分析 纯\(\t ...

  7. JDK9的新特性:String压缩和字符编码

    目录 简介 底层实现 总结 简介 String的底层存储是什么?相信大部分人都会说是数组.如果要是再问一句,那么是以什么数组来存储呢?相信不同的人有不同的答案. 在JDK9之前,String的底层存储 ...

  8. Docker 11 数据卷

    由来 Docker 是将应用和环境打包成一个镜像. 这样,数据就不应该保存在容器中,否则容器删除,数据就会丢失,有着非常大的风险. 为此,容器和主机之间需要有一个数据共享技术,使得在 Docker 容 ...

  9. 虚实相生,构建数智生活|HMS Core. Sparkle应用创新分论坛报名启动

    XR技术的发展,为用户带来了全新的体验模式.那么,作为支撑XR发展主要学科之一的图形学,将迎来哪些发展新机遇?移动应用开发者,该如何拥抱3D数字化转型? 7月15日,HDD·HMS Core. Spa ...

  10. 如何监控容器或K8s中的OpenSearch

    概述 当前 OpenSearch 使用的越来越多, 但是 OpenSearch 生态还不尽完善. 针对如下情况: 监控容器化或运行在 K8s 中的 OpenSearch 我查了下, 官方还没有提供完备 ...