SoFunction
Updated on 2025-03-04

Detailed explanation of the response method of Gin in Go language

Preface

This article introduces the Gin framework to process response data and supports responding to requests in formats such as strings, json, xml, and files.

Context objects support multiple return processing results, and the following are different response methods.

1. Respond to requests in a string

Return a string through the String function.

Function definition:

func (c *Context) String(code int, format string, values …interface{})

("/", func(c *) {
	(, "hello world")
})

2. Respond to requests in json format

The commonly used format when developing API interfaces is json. The following is an example of returning json format data.

// localhost:8080/user
type User struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}
("/user", func(c *) {
	u := &User{
		Name: "lucifer",
		Age:  18,
	}
	(, u)
})

3. Respond to requests in xml format

When developing API interfaces, there are also responses using xml format. The following is an example of returning xml format data.

// localhost:8080/student
type Student struct {
	Name string `xml:"name"`
	Age  int    `xml:"age"`
}
("/student", func(c *) {
	s := &Student{
		Name: "lucifer",
		Age:  19,
	}
	(, s)
})

4. Respond to requests in file format

The following description is how the gin framework can directly return a file, which can be used for file download.

// 4.1 Return directly("/file", func(c *) {
	("./")
})
// 4.2 Return the file and specify the download file name("/filename", func(c *) {
	("./", "change_file_name.txt")
})

5. Example

package main

import (
	"/gin-gonic/gin"
	"net/http"
)

/*
 Gin handles request parameters
 */
func main() {
	// 1. Instantiated service	r := ()

	// 2. Routing
	// 1. Return to string directly	// localhost:8080
	("/", func(c *) {
		(, "hello world")
	})

	// 2. Return json data	// localhost:8080/user
	type User struct {
		Name string `json:"name"`
		Age  int    `json:"age"`
	}
	("/user", func(c *) {
		u := &User{
			Name: "lucifer",
			Age:  18,
		}
		(, u)
	})

	// 3. Return xml data	// localhost:8080/student
	type Student struct {
		Name string `xml:"name"`
		Age  int    `xml:"age"`
	}
	("/student", func(c *) {
		s := &Student{
			Name: "lucifer",
			Age:  19,
		}
		(, s)
	})
	
	// 4. Return to the file	// 4.1 Return directly	("/file", func(c *) {
		("./")
	})
	// 4.2 Return the file and specify the download file name	("/filename", func(c *) {
		("./", "change_file_name.txt")
	})

	// 3. Start the service	(":8080")
}

Summarize

This is the article about the response method of Go Gin. For more information about Go Gin processing, please search for my previous articles or continue browsing the related articles below. I hope you will support me in the future!