gin学习1-7

package main

import (
    "github.com/gin-gonic/gin"
    "net/http"
)

// 响应json还有其他响应差不多可以去学
func _string(c *gin.Context) {
    c.String(http.StatusOK, "lalal")
}
func _json(c *gin.Context) {
    //json响应结构体
    type UsetInfo struct {
       UserNmae string `json:"user_name"` //这个可以在json序列化是去改变这个名
       Age      int
       Password string `json:"-"` //不渲染,不进行json序列化,忽略转换为json
    }
    //user := UsetInfo{"xiao", 23, "1234"}
    //直接响应json
    c.JSON(200, gin.H{
       "name": "lala", //要写,号
    })
}

// 重定向 当用户输入一个对应路径是跳转到你指定的网页去
func _redirect(c *gin.Context) {
    c.Redirect(302, "http://127.0.0.1/lala.png")
}
func main() {
    //创建一个默认的路由
    router := gin.Default()
    //加载这个目录下的所有模板文件,目录名用你自己创建的
    // router.LoadHTMLGlob("templates/*")
    //网页请求这个静态目录的前缀,第二个是一个目录
    router.StaticFS("/static", http.Dir("static/static"))
    //下载某一个文件前面是网站访问路径,后面是文件路径,在goland中只有相对于项目的路径,单个文件
    router.StaticFile("/lala.png", "static/日落.png")
    //绑定路由规则和路由函数,访问/index的路由,将用对应的函数去处理,这是一个匿名函数没有函数名,
    //因为go 规定有名字的函数里面不能在声明有名字的函数但是匿名的可以
    router.GET("/", _string)
    //context.String(http.StatusOK, "hello lalala")响应一返回字符串
    router.GET("/json", _json)
    //启动监听,gin会把web服务运行在本机的0.0.0.0:8080端口上
    //router.GET("/baidu", _redirect)
    router.GET("/baidi", _redirect)
    //端口80是默认端口,你甚至不用在127.0.0.1后面加80
    router.Run(":80") //router.Run的本质就是对http.ListenAndServer的封装
    //原生http服务的方式 http.ListenAndServer(":8080",router)

}

相关推荐

  1. gin学习1-7

    2024-04-29 05:50:05       29 阅读
  2. CentOS7安装git-2.42.1

    2024-04-29 05:50:05       52 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-29 05:50:05       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-29 05:50:05       101 阅读
  3. 在Django里面运行非项目文件

    2024-04-29 05:50:05       82 阅读
  4. Python语言-面向对象

    2024-04-29 05:50:05       91 阅读

热门阅读

  1. addEventListener()方法中的参数,以及作用

    2024-04-29 05:50:05       34 阅读
  2. Linux基础 -- Linux 中使用 system 函数的返回值转换

    2024-04-29 05:50:05       29 阅读
  3. 系统服务器选型

    2024-04-29 05:50:05       36 阅读
  4. C#基础之选择排序

    2024-04-29 05:50:05       34 阅读
  5. SQL注入攻击:原理与防御策略

    2024-04-29 05:50:05       35 阅读
  6. Threejs加载字体加载FontLoader与TTFLoader

    2024-04-29 05:50:05       33 阅读
  7. 为什么多线程需要互斥,多进程不需要?

    2024-04-29 05:50:05       37 阅读
  8. Leetcode 第395场周赛 问题和解法

    2024-04-29 05:50:05       33 阅读