In the previous section we outlined the functional modules required for the Golang blog backend, starting with the backend setup.

In the background setup, we split it into four pieces. They are: global Settings, function Settings, home TDK Settings, navigation Settings.

Global Settings in background Settings

Global Settings include the website name, website address, website logo, record number, copyright information, background address, website status, site closure prompt and other information.

  • Site name The site name is used to call the front-end blog page, generally, in SEO functions, generally used to add a suffix for the title and other places.
  • Website address refers to the website address, such as www.kandaoni.com, which is used to generate the absolute address of the whole site.
  • Website logo can be easily replaced in the background logo, website logo is the soul of a website, of course, it is not necessary to set if not set, the front header will be replaced by the site name, if set, the logo will be displayed.
  • Put on record the number of recent domestic to put on record inspection more and more strict, do not put on record website, cannot go on line in domestic server, put on record, also must hang put on record number, and want to connect to put on record center. Therefore, add a place to fill in the record number, which can be conveniently set up. After filling in the record number, the front desk call, will automatically add jump to the record center connection, no longer afraid of the record was cancelled.
  • Copyright information here can be customized copyright information, used to display in the blog footer place, equivalent to SEO optimization in one sentence navigation, here you can layout keywords, increase the efficiency of keyword optimization home page.
  • Background address is often a website is easy to be invaded, background address exposure accounted for a great reason. The advantage of this feature is that you can customize the background address and never worry about exposing the background address.
  • If you don’t want to open your blog for the time being, you can set the status of your blog to closed. Of course, in addition to the background, the background is still accessible, or you can no longer open the site.
  • Close the site prompt with the state of the site to use, when closed the site, want to show the content.

Let’s implement the front-end page first. Create a setting folder under manage/ SRC /views/ and add system.html:

<title>Global Settings</title>

<div class="layui-card layadmin-header">
  <div class="layui-breadcrumb" lay-filter="breadcrumb">
    <a lay-href="">The background page</a>
    <a><cite>The background is set</cite></a>
    <a><cite>Global Settings</cite></a>
  </div>
</div>

<div class="layui-fluid">
  <div class="layui-row layui-col-space15">
    <div class="layui-col-md12">
      <div class="layui-card">
        <div class="layui-card-header">Global Settings</div>
        <div class="layui-card-body" pad15>
          <script type="text/html" template lay-url="/setting/system" lay-done="layui.form.render();">
            <div class="layui-form" style="padding: 20px 0 0 0;">
          <div class="layui-form-item">
            <label class="layui-form-label">Web site name</label>
            <div class="layui-input-inline">
              <input type="text" name="site_name" value="{{ d.data.site_name || ' ' }}"  lay-verify="required" placeholder="Please enter... (required)" autocomplete="off" class="layui-input">
            </div>
            <div class="layui-form-mid layui-word-aux">The name appears as a suffix on the site title</div>
          </div>
          <div class="layui-form-item">
            <label class="layui-form-label">Web site address</label>
            <div class="layui-input-inline">
              <input type="text" name="base_url" value="{{ d.data.base_url || ' ' }}"  lay-verify="required" placeholder="Please enter... (required)" autocomplete="off" class="layui-input">
            </div>
            <div class="layui-form-mid layui-aux-word">The url of a web site, such as https://www.kandaoni.com, used to generate the absolute address of the site</div>
          </div>
          <div class="layui-form-item">
            <label class="layui-form-label">The website LOGO</label>
            <div class="layui-input-inline">
              <button type="button" class="layui-btn" id="site-logo">
                <i class="layui-icon">&#xe67c;</i>To upload pictures</button>
            </div>
            <div class="layui-form-mid">
              <input type="hidden" name="site_logo" value="{{ d.data.site_logo || ' ' }}" id="site-logo-input">
              <img src="{{ d.data.site_logo || ' ' }}" class="site-logo-img" id="site-logo-img"/>
            </div>
            <div class="layui-form-mid layui-word-aux">The site LOGO is displayed in the header</div>
          </div>
          <div class="layui-form-item">
            <label class="layui-form-label">The record number</label>
            <div class="layui-input-inline">
              <input type="text" name="site_icp" value="{{ d.data.site_icp || ' ' }}" autocomplete="off" class="layui-input">
            </div>
            <div class="layui-form-mid layui-word-aux">ICP record query address:<a href="https://beian.miit.gov.cn/" target="_blank">beian.miit.gov.cn</a>, just fill in the main record number. If not, do not fill in.</div>
          </div>
          <div class="layui-form-item">
            <label class="layui-form-label">Copyright information</label>
            <div class="layui-input-inline">
              <textarea class="layui-textarea" name="site_copyright" rows="3">{{ d.data.site_copyright || ' ' }}</textarea>
            </div>
            <div class="layui-form-mid layui-word-aux">The copyright information is displayed at the bottom of the page</div>
          </div>
          <div class="layui-form-item">
            <label class="layui-form-label">The background path</label>
            <div class="layui-input-inline">
              <input type="text" name="admin_uri" value="{{ d.data.admin_uri || ' ' }}" autocomplete="off" class="layui-input">
            </div>
            <div class="layui-form-mid layui-word-aux">You can customize the background access path to reduce the probability of exposure. Such as<cite>/manage</cite>. The modification takes effect only after a restart</div>
          </div>
          <div class="layui-form-item">
            <label class="layui-form-label">Site condition</label>
            <div class="layui-input-inline">
              <input type="radio" name="site_close" value="0" title="Normal" {{ d.data.site_close! =1 ? 'checked' : ' ' }}>
              <input type="radio" name="site_close" value="1" title="Close your station" {{ d.data.site_close= =1 ? 'checked' : ' ' }}>
            </div>
          </div>
          <div class="layui-form-item">
            <label class="layui-form-label">Closed station hints</label>
            <div class="layui-input-inline">
              <textarea class="layui-textarea" name="site_close_tips" rows="3">{{ d.data.site_close_tips || ' ' }}</textarea>
            </div>
            <div class="layui-form-mid layui-word-aux">The above prompt will be displayed when the site is closed. Support for HTML tags</div>
          </div>
          
          <div class="layui-form-item">
            <label class="layui-form-label"></label>
            <div class="layui-input-inline">
              <input type="button" lay-submit lay-filter="system-submit" value="Confirm" class="layui-btn">
            </div>
          </div>
        </div>
        </script>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
  layui.use('setting', layui.factory('setting'));
</script>
Copy the code

HTML part of the code is relatively simple, just copy, inside the script wrapped HTML, will automatically render.

Then create a setting.js file under manage/ SRC /controller/ :

/ * *@Name: layuiAdmin Settings@Author: good heart@Site: http://www.layui.com/admin/.@License: LPPL
    
 */
 
layui.define(['form'.'upload'.'table'].function(exports){
  var $ = layui.$
  ,layer = layui.layer
  ,laytpl = layui.laytpl
  ,setter = layui.setter
  ,view = layui.view
  ,admin = layui.admin
  ,form = layui.form
  ,table = layui.table
  ,upload = layui.upload;

  / / upload logo
  var uploadInst = upload.render({
    elem: '#site-logo' // Bind the element
    ,url: '/attachment/upload' // Upload interface
    ,done: function(res){
      // Callback after upload
      $('#site-logo-input').val(res.data.src);
      $('#site-logo-img').prop('src', res.data.src); },error: function(){
      // Request exception callback
      layer.msg("Upload error"); }});// Site Settings
  form.on('submit(system-submit)'.function(obj){
    delete obj.field.file;
    obj.field.site_close = Number(obj.field.site_close);
    admin.req({
      url: '/setting/system'
      ,data: obj.field
      ,type: 'post'
      ,done: function(res){
        layer.msg(res.msg, {
          offset: '15px'
          ,icon: 1}); },fail: function(res){
        layer.msg(res.msg, {
          offset: '15px'
          ,icon: 2}); }}); });// Exposed interface
  exports('setting'{}); });Copy the code

In the global Settings, we need form submission, and blog site logo upload, so in JS, we have implemented two parts of the function, one is to upload pictures, the other is to submit the form. And since our background is written in Golang, which is a strongly typed language, we need to convert the numeric string to a numeric type when submitting the form:

obj.field.site_close = Number(obj.field.site_close);
Copy the code

With the front page done, we can then implement the Golang part of the code:

Background global Settings function realization

Then the controller/manageController folder to create a setting. Go file:

package manageController

import (
	"github.com/kataras/iris/v12"
	"irisweb/config"
	"irisweb/model"
	"irisweb/provider"
	"irisweb/request"
	"strings"
)

func SettingSystem(ctx iris.Context) {
	system := config.JsonData.System

	ctx.JSON(iris.Map{
		"code": config.StatusOK,
		"msg":  ""."data": system,
	})
}

func SettingSystemForm(ctx iris.Context) {
	var req request.SystemConfig
	iferr := ctx.ReadJSON(&req); err ! =nil {
		ctx.JSON(iris.Map{
			"code": config.StatusFailed,
			"msg":  err.Error(),
		})
		return
	}

	if! strings.HasPrefix(req.AdminUri,"/") | |len(req.AdminUri) < 2 {
		ctx.JSON(iris.Map{
			"code": config.StatusFailed,
			"msg":  "Background path needs to start with/",})return
	}

	config.JsonData.System.SiteName = req.SiteName
	config.JsonData.System.SiteLogo = req.SiteLogo
	config.JsonData.System.SiteIcp = req.SiteIcp
	config.JsonData.System.SiteCopyright = req.SiteCopyright
	config.JsonData.System.AdminUri = req.AdminUri
	config.JsonData.System.SiteClose = req.SiteClose
	config.JsonData.System.SiteCloseTips = req.SiteCloseTips

	err := config.WriteConfig()
	iferr ! =nil {
		ctx.JSON(iris.Map{
			"code": config.StatusFailed,
			"msg":  err.Error(),
		})
		return
	}

	ctx.JSON(iris.Map{
		"code": config.StatusOK,
		"msg":  "Configuration updated"})},Copy the code

Here we need to implement two functions: SettingSystem(), which reads the global configuration, and SettingSystemForm(), which saves the global configuration.

Since we store global configuration and other configuration information in config.json, we also need to add the corresponding configuration in config folder:

Add setting.go to config folder:

package config

type systemConfig struct {
	SiteName      string `json:"site_name"`
	SiteLogo      string `json:"site_logo"`
	SiteIcp       string `json:"site_icp"`
	SiteCopyright string `json:"site_copyright"`
	BaseUrl       string `json:"base_url"`
	AdminUri      string `json:"admin_uri"`
	SiteClose     int    `json:"site_close"`
	SiteCloseTips string `json:"site_close_tips"`
}
Copy the code

Config /config.go and add a reference to systemConfig in the struct of configData:

type configData struct {
	DB     mysqlConfig  `json:"mysql"`
	Server serverConfig `json:"server"`
	//setting
  System  systemConfig  `json:"system"`
}
Copy the code

Since our configuration allows the background to set a custom background address, but this is empty by default, we also need to give a default background address, modify initJSON() function, add the corresponding code:

	// Add default values to the background
	if JsonData.System.AdminUri == "" {
		JsonData.System.AdminUri = "/manage"
	}
Copy the code

After the config part is configured, we can add the back-end route to realize the global setting of the first configuration item in the background.

In order to distinguish between them, we added manage.go file under route folder to store and manage background routes uniformly:

package route

import (
	"fmt"
	"github.com/kataras/iris/v12"
	"irisweb/config"
	"irisweb/controller"
	"irisweb/controller/manageController"
	"irisweb/middleware"
)

func manageRoute(app *iris.Application) {
	manage := app.Party(config.JsonData.System.AdminUri, controller.Inspect)
	{
		manage.HandleDir("/", fmt.Sprintf("%smanage", config.ExecPath))
		manage.Post("/user/login", manageController.UserLogin)

		user := manage.Party("/user", middleware.ManageAuth)
		{
			user.Get("/detail", manageController.UserDetail)
			user.Post("/detail", manageController.UserDetailForm)
			user.Post("/logout", manageController.UserLogout)
		}

		setting := manage.Party("/setting", middleware.ManageAuth)
		{
			setting.Get("/system", manageController.SettingSystem)

			setting.Post("/system", manageController.SettingSystemForm)
		}
	}
}
Copy the code

The routing, we use the app. Party (config) JsonData) System. AdminUri, controller, Inspect), to set up dynamic binding the background background access path.

This is the first step in our implementation of the background. Once that’s done, we launch the Golang project to verify the results, and if nothing goes wrong, we can change the global Settings.

Tutorial use case source code

The complete project sample code is hosted on GitHub at github.com/fesiong/gob… You can view the complete tutorial project source code, it is recommended to view the tutorial at the same time, carefully control the source code, can effectively improve the code speed and deepen the understanding of the blog project. It is recommended to fork a copy directly to make changes on it. Welcome to Star.