Gin go learning Note 6: preparation of gin web framework Api

Api writing

1> The data formats returned by the Api of the Gin framework are JSON, XML and yaml. Yaml is a special data format. (I haven't implemented the operation of getting nodes for the time being.)

2> In the apis folder, create a new data.go file as the business logic code to obtain api data. The specific code is as follows:

   

package apis

import (
  "net/http"
  "github.com/gin-gonic/gin"
 . "GinLearn/GinLearn/models"
)
//Page called by Api
func GetApiHtml(c *gin.Context){
	c.HTML(http.StatusOK,"api.html",gin.H{
		"title":"Go-Gin Api Call page",
	})
}
//Data in Json format
func GetJsonData(c *gin.Context) {  
  //Get requested parameters
  search:=c.PostForm("search")
  //Get user's data
  datalist:=GetPersonList(1,10,search)
  //Total number of records obtained
  count:=GetRecordNum(search)
 //Return results
 c.JSON(http.StatusOK, gin.H{
  "datalist": datalist,
  "count":count,
  "pagesize":3,
  "pageno":1,
 })
}

//Data in Xml format
func GetXmlData(c *gin.Context) {  
	//Get requested parameters
	search:=c.PostForm("search")
	//Get user's data
	datalist:=GetPersonList(1,10,search)
	//Total number of records obtained
	count:=GetRecordNum(search)
   //Return results
   c.XML(http.StatusOK, gin.H{
	"datalist": datalist,
	"count":count,
	"pagesize":3,
	"pageno":1,
   })
}

//Data in Xml format
func GetYamlData(c *gin.Context) {  
	//Get requested parameters
	search:=c.PostForm("search")
	//Get user's data
	datalist:=GetPersonList(1,10,search)
	//Total number of records obtained
	count:=GetRecordNum(search)
   //Return results
   c.YAML(http.StatusOK, gin.H{
	"datalist": datalist,
	"count":count,
	"pagesize":3,
	"pageno":1,
   })
  }

  //Data in Json format
func GetParamsJsonData(c *gin.Context) {  
	//Get requested parameters
	search:=c.PostForm("search")
	//Get user's data
	datalist:=GetPersonList(1,10,search)
	//Total number of records obtained
	count:=GetRecordNum(search)
   //Return results
   c.JSON(http.StatusOK, gin.H{
	"datalist": datalist,
	"count":count,
	"pagesize":3,
	"pageno":1,
	"search":search,
   })
  }

  

3> Create a new api.html page in the views folder as a display page for testing to obtain API data. The specific code is as follows:

   

<!DOCTYPE html>
 
<html>
      <head>
        <title>{{.title}}</title>
        <link rel="shortcut icon" href="/static/img/favicon.png" /> 
        <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.css"/>
        <script type="text/javascript" src="/static/js/jquery-2.1.1.min.js"></script> 
        <script type="text/javascript" src="/static/bootstrap/js/bootstrap.min.js"></script> 
      </head>       
    <body>
       <div class="container">
        <!--Request dictionary data--> 
        <div style="width:100%;height:50px;">
            <input type="text" id="search" placeholder="Please enter parameters"/>
            <button onclick="getparams()" class="btn btn-primary">Get the parameters</button>
            <label id="txtparams"></label>
        </div>
        <!--Request to get Json data--> 
        <div style="width:100%;height:50px;">
          <button onclick="getjson()" class="btn btn-primary">obtain Json</button>
          <label id="txtjson"></label>
        </div>
        <!--Request to get Xml data--> 
        <div style="width:100%;height:50px;">
            <button onclick="getxml()" class="btn btn-primary">obtain Xml</button>
            <label id="txtxml"></label>
        </div>
        <!--Request to get Yaml data--> 
        <div style="width:100%;height:50px;">
          <button onclick="getYaml()" class="btn btn-primary">obtain Yaml</button>
          <label id="txtyaml"></label>
        </div>       
       </div>
       
        <!--JS Part-->
        <script type="text/javascript">
         //Get the parameters
         function getparams(){
            $.ajax({
               type:'get',
               url:'/api/paramsdata',//Here is the format of json data
               data:{
                search:$("#search").val()
               },
               success:function(result){
                   console.log('Get data for parameters')
                   console.log(result)
                  $("#txtparams").html(" total records: "+ result.count
                   +",Record I:"+result.datalist[0].first_name+result.datalist[0].last_name+",Record II:"
                   +result.datalist[1].first_name+result.datalist[1].last_name+"...");
               } 
            })
          }
          //Get Json
          function getjson(){
            $.ajax({
               type:'get',
               url:'/api/jsondata',
               dataType:'json',//Here is the format of json data
               data:{
                 search:$("#search").val()
               },
               success:function(result){
                   console.log('Obtain json Data for')
                   console.log(result)
                   $("#Txtjson). HTML ("the result of JSON:" + result.count
                   +",Record 1:"+result.datalist[0].first_name+result.datalist[0].last_name+",Record 2:"
                   +result.datalist[1].first_name+result.datalist[1].last_name+"...");
               } 
            })
          }
          //Get Xml
          function getxml(){
            $.ajax({
               type:'get',
               url:'/api/xmldata',
               dataType:'xml',//Here is the format of the xml data
               data:{
                 search:$("#search").val()
               },
               success:function(result){
                   console.log('Obtain xml Data for')
                   console.log(result)
                   
                 $("#Txtxtxml "). HTML (" the result of XML: "+ $(result).text());
               } 
            })
          }
           //Get yaml
           function getYaml(){
            $.ajax({
               type:'get',
               url:'/api/yamldata', 
               data:{
                search:$("#search").val()
               },
               success:function(result){
                   console.log('Obtain yaml Data for')
                   console.log(result)
                  $("#txtyaml").html("yaml result: "+ result);
               } 
            })
          }
         
        </script>
    </body>
</html>

  

4> Add the route of api part in router.go. The specific code is as follows:

    

package routers

import (
  "github.com/gin-gonic/gin"
  . "GinLearn/GinLearn/apis" //api part
  . "GinLearn/GinLearn/controllers" //Constroler part
 )
 
func InitRouter() *gin.Engine{
  router := gin.Default()
  //Hello World
  router.GET("/", IndexApi)
  //Rendering html pages
  router.LoadHTMLGlob("views/*")
  router.GET("/home/index", ShowHtmlPage)
  //List page
  router.GET("/home/list", ListHtml)
  router.POST("/home/PageData", GetDataList)
  router.POST("/home/PageNextData", PageNextData)

  //New page
  router.GET("/home/add", AddHtml)
  router.POST("/home/saveadd", AddPersonApi)
  
   //Edit page
   router.GET("/home/edit", EditHtml)
   router.POST("/home/saveedit", EditPersonApi)

    //delete
    router.POST("/home/delete", DeletePersonApi)

    //Bootstrap layout page
    router.GET("/home/bootstrap", Bootstraphtml)

    //File upload and download 
    router.GET("/home/fileopt", Fileopthtml)
    router.POST("/home/fileuplaod", Fileupload)
    router.GET("/home/filedown", Filedown)

    //Creating, deleting, reading and writing files
    router.GET("/home/filerw", Filerwhtml)
    router.POST("/home/addfile", FilerCreate)//create a file
    router.POST("/home/writefile", FilerWrite)//write file
    router.POST("/home/readfile", FilerRead)//read file
    router.POST("/home/deletefile", FilerDelete)//Delete file
    
    //Part of api call
    router.GET("/home/api", GetApiHtml) 
    router.GET("/api/jsondata", GetJsonData) 
    router.GET("/api/xmldata", GetXmlData) 
    router.GET("/api/yamldata", GetYamlData) 
    router.GET("/api/paramsdata", GetParamsJsonData) 
    return router
 }
 

  

5> The specific effect of compilation test is as follows:

 

 

6> The next chapter is about layout page

Tags: Go JSON xml Javascript github

Posted on Mon, 04 May 2020 04:14:13 -0700 by Levan