{"id":1391,"date":"2020-03-08T01:08:42","date_gmt":"2020-03-07T17:08:42","guid":{"rendered":"https:\/\/wyxxt.org.cn\/?p=1391"},"modified":"2023-12-04T15:45:55","modified_gmt":"2023-12-04T07:45:55","slug":"gin%e6%a1%86%e6%9e%b6%e7%ae%80%e4%bb%8b%ef%bc%881%ef%bc%89","status":"publish","type":"post","link":"https:\/\/wyxxt.org.cn\/?p=1391","title":{"rendered":"Gin\u6846\u67b6\u7b80\u4ecb"},"content":{"rendered":"<h3>\u6574\u4f53\u67b6\u6784<\/h3>\n<pre><code class=\"language-go\">package main\n\nimport (\n    \"net\/http\"\n\n    \"github.com\/gin-gonic\/gin\"\n)\n\nfunc main() {\n    r := gin.Default()\n    r.GET(\"\/\", func(c *gin.Content) {\n        c.JSON(http.StatusOK, gin.H{\n        \"code\": \"P10001\"\n        })\n    })\n    r.Run()\n}<\/code><\/pre>\n<h3>\u8be6\u89e3<\/h3>\n<h4>\u76f4\u63a5\u83b7\u53d6\u8bf7\u6c42\u53c2\u6570<\/h4>\n<pre><code class=\"language-go\">\/\/ parameters in path\nc.Param(\"name\")\n\n\/\/ querystring param\nc.DefaultQuery(\"name\", \"Guest\")\nc.Query(\"name\")\n\n\/\/form\nc.PostForm(\"name\")\nc.DefaultPostForm(\"name\", \"Guest\")\n<\/code><\/pre>\n<pre><code class=\"language-go\">\/\/ map as querystring or postform parameters\nids := c.QueryMap(\"ids\")\nnames := c.PostFormMap(\"names\")\nc.JSON(http.StatusOK, gin.H{\n    \"ids\":   ids,\n    \"names\": names,\n})<\/code><\/pre>\n<p><img decoding=\"async\" src=\"https:\/\/oss.wyxxt.org.cn\/images\/2021\/09\/18\/image-1583483127300.png\" alt=\"file\" \/><\/p>\n<h4>\u6587\u4ef6\u4e0a\u4f20<\/h4>\n<pre><code class=\"language-go\">\/\/ upload file\nfile, _ := c.FormFile(\"file\")\n\/\/ Upload the file to specific dst.\n\/\/ c.SaveUploadedFile(file, dst)\n\n\/\/ multiple files\nform, _ := c.MultipartForm()\nfiles := form.File[\"upload[]\"]<\/code><\/pre>\n<h4>\u8def\u7531<\/h4>\n<pre><code class=\"language-go\">\/\/grouping routes\nv1 := router.Group(\"\/v1\")\n{\n    v1.POST(\"\/login\", loginEndpoint)\n    v1.POST(\"\/submit\", submitEndpoint)\n    v1.POST(\"\/read\", readEndpoint)\n}<\/code><\/pre>\n<h4>\u4e2d\u95f4\u4ef6middleware<\/h4>\n<pre><code class=\"language-go\">\/\/use r := gin.New() instead of r := gin.Default()\nr := gin.New()\nr.Use(gin.Logger())\nauthorized := r.Group(\"\/\")\nauthorized.Use(AuthRequired())\n{\n    authorized.POST(\"\/login\", loginEndpoint)\n    authorized.POST(\"\/submit\", submitEndpoint)\n    authorized.POST(\"\/read\", readEndpoint)\n}<\/code><\/pre>\n<h4>\u65e5\u5fd7<\/h4>\n<pre><code class=\"language-go\">\/\/ write log file\n\n\/\/ Disable Console Color, you don't need console color when writing the logs to file.\ngin.DisableConsoleColor()\n\n\/\/ Logging to a file.\nf, _ := os.Create(\"gin.log\")\ngin.DefaultWriter = io.MultiWriter(f)\n\/\/ Use the following code if you need to write the logs to file and console at the same time.\n\/\/ gin.DefaultWriter = io.MultiWriter(f, os.Stdout)\n<\/code><\/pre>\n<h4>Model binding and validation<\/h4>\n<blockquote><p>\nMust bind<\/p>\n<ul>\n<li>Bind, BindJSON, BindXML, BindQuery, BindYAML, BindHeader<\/li>\n<\/ul>\n<p>Should bind<\/p>\n<ul>\n<li>ShouldBind, ShouldBindJSON, ShouldBindXML, ShouldBindQuery, ShouldBindYAML, ShouldBindHeader<\/li>\n<\/ul>\n<\/blockquote>\n<pre><code class=\"language-go\">type Login struct {\n    User     string <code>form:\"user\" json:\"user\" xml:\"user\"  binding:\"required\"<\/code>\n    Password string <code>form:\"password\" json:\"password\" xml:\"password\" binding:\"required\"<\/code>\n}\nfunc main() {\n    r := gin.Default()\n\n    \/\/ Example for binding JSON ({\"user\": \"manu\", \"password\": \"123\"})\n    r.POST(\"\/loginJSON\", func(c *gin.Context) {\n        var json Login\n        if err := c.ShouldBindJSON(&json); err != nil {\n            c.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n            return\n        }\n        if json.User != \"manu\" || json.Password != \"123\" {\n            c.JSON(http.StatusUnauthorized, gin.H{\"status\": \"unauthorized\"})\n            return\n        }\n        c.JSON(http.StatusOK, gin.H{\"status\": \"you are logged in\"})\n    })<\/code><\/pre>\n<blockquote><p>\nValidators<br \/>\n\/\/todo\n<\/p><\/blockquote>\n<h4>\u9759\u6001\u6587\u4ef6\u670d\u52a1<\/h4>\n<pre><code class=\"language-go\">r.Static(\"\/assets\", \".\/assets\")<\/code><\/pre>\n<h4>HTML\u6e32\u67d3<\/h4>\n<pre><code class=\"language-go\">r := gin.Default()\nr.LoadHTMLGlob(\"templates\/*\")\n    \/\/router.LoadHTMLFiles(\"templates\/template1.html\", \"templates\/template2.html\")\n    r.GET(\"\/index\", func(c *gin.Context) {\n        c.HTML(http.StatusOK, \"index.tmpl\", gin.H{\n            \"title\": \"Main website\",\n        })\n    })<\/code><\/pre>\n<pre><code class=\"language-html\">\/\/templates\/index.tmpl\n\n<html>\n    <h1>\n        {{ .title }}\n    <\/h1>\n<\/html><\/code><\/pre>\n<pre><code class=\"language-go\">func main() {\n    router := gin.Default()\n    router.LoadHTMLGlob(\"templates\/**\/*\")\n    router.GET(\"\/posts\/index\", func(c *gin.Context) {\n        c.HTML(http.StatusOK, \"posts\/index.tmpl\", gin.H{\n            \"title\": \"Posts\",\n        })\n    })\n    router.GET(\"\/users\/index\", func(c *gin.Context) {\n        c.HTML(http.StatusOK, \"users\/index.tmpl\", gin.H{\n            \"title\": \"Users\",\n        })\n    })\n    router.Run(\":8080\")\n}<\/code><\/pre>\n<pre><code class=\"language-html\">{{ define \"posts\/index.tmpl\" }}\n<html><h1>\n    {{ .title }}\n<\/h1>\nUsing posts\/index.tmpl\n<\/html>\n{{ end }}<\/code><\/pre>\n<pre><code class=\"language-html\">{{ define \"users\/index.tmpl\" }}\n<html><h1>\n    {{ .title }}\n<\/h1>\nUsing users\/index.tmpl\n<\/html>\n{{ end }}<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>\u6574\u4f53\u67b6\u6784 package main import ( &#8220;net\/http&#8221; &#8220;github.com\/gin-g [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[15],"tags":[398],"class_list":["post-1391","post","type-post","status-publish","format-standard","hentry","category-15","tag-go"],"_links":{"self":[{"href":"https:\/\/wyxxt.org.cn\/index.php?rest_route=\/wp\/v2\/posts\/1391","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/wyxxt.org.cn\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/wyxxt.org.cn\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/wyxxt.org.cn\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/wyxxt.org.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=1391"}],"version-history":[{"count":7,"href":"https:\/\/wyxxt.org.cn\/index.php?rest_route=\/wp\/v2\/posts\/1391\/revisions"}],"predecessor-version":[{"id":2155,"href":"https:\/\/wyxxt.org.cn\/index.php?rest_route=\/wp\/v2\/posts\/1391\/revisions\/2155"}],"wp:attachment":[{"href":"https:\/\/wyxxt.org.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=1391"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/wyxxt.org.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=1391"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/wyxxt.org.cn\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=1391"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}