Golang Gin Tips

Source: Internet
Author: User

First, the HTML code directly in the HTML template output

Gin document It's a little bit of a hole in my dad. If you don't use HTML templates to insert HTML code directly into your go code, you'll find a half-day solution if you're not familiar with go template.

Solution:

use template. HTML.

Example:
Index.tmpl file:

{{.data1}} {{.data2}}

Go code:

c.HTML(http.StatusOK, "index.tmpl", gin.H{        "data1": "<p> test </p>"        "data2":  template.HTML("<p> test </p>"),    })

The HTML returned is:

<p> test </p>test

Second, traverse all param of postform

I did not find all the Param APIs in the form that traverse the post submission, so I wrote this method with reference to the source code:

func updatePostPage(c *gin.Context) {    req := c.Request    req.ParseForm()    req.ParseMultipartForm(32 << 20)//参数相当于32M,官方源码中本来定义了个变量,但是是private类型不能直接调用,所以干脆直接写个值。    h := gin.H{}    for k, v := range req.PostForm {        if len(v) > 0 {            println(k, v[0])            h[k] = v[0]        }    }    c.JSON(http.StatusOK, h)}

Third, the output of beautiful JSON

    1. Use c.IndentedJSON overrides c.JSON .
    2. If you are using a JSON library that comes with Golang, use:
ret, err := json.MarshalIndent(h, "", "\t")

Substitution json.Marshal can get pretty json.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.