添加验证码邮件相关接口
parent
b133067a85
commit
974c3d6fc8
|
@ -1,4 +1,5 @@
|
||||||
package controller
|
package controller
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"crypto/md5"
|
"crypto/md5"
|
||||||
|
@ -10,18 +11,19 @@ import (
|
||||||
_ "github.com/go-sql-driver/mysql"
|
_ "github.com/go-sql-driver/mysql"
|
||||||
"github.com/tommy351/gin-sessions"
|
"github.com/tommy351/gin-sessions"
|
||||||
"io"
|
"io"
|
||||||
"strconv"
|
|
||||||
"time"
|
|
||||||
"user/logs"
|
|
||||||
"log"
|
"log"
|
||||||
"math/rand"
|
"math/rand"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/smtp"
|
"net/smtp"
|
||||||
"regexp"
|
"regexp"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"user/redis"
|
"time"
|
||||||
"user/model"
|
"user/config"
|
||||||
"user/db"
|
"user/db"
|
||||||
|
"user/logs"
|
||||||
|
"user/model"
|
||||||
|
"user/redis"
|
||||||
)
|
)
|
||||||
|
|
||||||
type ReqSendEmailCode struct {
|
type ReqSendEmailCode struct {
|
||||||
|
@ -117,99 +119,79 @@ func GetUser(c *gin.Context) {
|
||||||
// @Param department_id query string false "name search by q"
|
// @Param department_id query string false "name search by q"
|
||||||
// @Param permission_type query string false "name search by q"
|
// @Param permission_type query string false "name search by q"
|
||||||
// @Router /api/users [get]
|
// @Router /api/users [get]
|
||||||
func GetUsers(c *gin.Context) {
|
func Users(c *gin.Context) {
|
||||||
var statuscode int
|
var statuscode int
|
||||||
var resp RespBase
|
var resp RespBase
|
||||||
|
|
||||||
resp.Msg = "获取失败"
|
resp.Msg = "获取失败"
|
||||||
resp.Status = 0
|
resp.Status = 0
|
||||||
statuscode = 200
|
statuscode = 200
|
||||||
|
|
||||||
defer func() {
|
defer func() {
|
||||||
c.JSON(statuscode,resp)
|
c.JSON(statuscode,resp)
|
||||||
}()
|
}()
|
||||||
//获取用户组信息
|
offset := c.Query("offset")
|
||||||
var page int
|
limit := c.Query("limit")
|
||||||
var pageSize int
|
ioffset,e := strconv.Atoi(offset)
|
||||||
var displayname string
|
|
||||||
var department_id string
|
|
||||||
var permission_type string
|
|
||||||
|
|
||||||
displayname = c.Query("displayname")
|
|
||||||
department_id = c.Query("department_id")
|
|
||||||
permission_type = c.Query("permission_type")
|
|
||||||
|
|
||||||
if c.Query("page") == ""{
|
|
||||||
page = 0
|
|
||||||
}else {
|
|
||||||
var err error
|
|
||||||
page,err = strconv.Atoi(c.Query("page"))
|
|
||||||
if err != nil{
|
|
||||||
logs.Error("error ato i ")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
log.Println(pageSize,page)
|
|
||||||
if c.Query("pageSize") == ""{
|
|
||||||
pageSize = 10
|
|
||||||
}else {
|
|
||||||
var err error
|
|
||||||
pageSize,err = strconv.Atoi(c.Query("pageSize"))
|
|
||||||
if err != nil{
|
|
||||||
logs.Error("error ato i ")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
session := sessions.Get(c)
|
|
||||||
userinfo := session.Get("")
|
|
||||||
var users map[string] interface{}
|
|
||||||
e := json.Unmarshal([]byte(userinfo.(string)),&users)
|
|
||||||
if nil != e{
|
if nil != e{
|
||||||
logs.Error(e.Error())
|
logs.Error(e.Error())
|
||||||
}
|
|
||||||
permission,ok := users["PermissionType"]
|
|
||||||
if !ok{
|
|
||||||
logs.Error("error could not find permission_type")
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// 部门组长只允许查看自己所在部门成员列表,且要过滤超级管理员
|
ilimit,er := strconv.Atoi(limit)
|
||||||
if permission == 1 && department_id != ""{
|
if nil != er{
|
||||||
d ,_ := users["DepartmentId"]
|
logs.Error(e.Error())
|
||||||
department_id = d.(string)
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
respdata := make(map[string]interface{},1)
|
dat := map[string] interface{}{}
|
||||||
var usersinfo []model.Users
|
users,all := model.GetUsers(int32(ilimit),int32(ioffset),"")
|
||||||
|
dat["users"] = users
|
||||||
if permission != 0{
|
dat["all"] = all
|
||||||
query := "select * from users "
|
|
||||||
if displayname != "" || department_id != "" ||permission_type != ""{
|
|
||||||
query += " where "
|
|
||||||
}
|
|
||||||
if displayname != ""{
|
|
||||||
query += fmt.Sprintf("display_name like '%%%s%%'",displayname)
|
|
||||||
}
|
|
||||||
if department_id != ""{
|
|
||||||
query += fmt.Sprintf("and department_id = %s",department_id)
|
|
||||||
}
|
|
||||||
if permission_type != ""{
|
|
||||||
query += fmt.Sprintf("and permission_type = %s ",permission_type)
|
|
||||||
}
|
|
||||||
query += "order by id ASC "
|
|
||||||
query += fmt.Sprintf("limit %d ",pageSize)
|
|
||||||
query += fmt.Sprintf(" offset %d ",pageSize*page)
|
|
||||||
|
|
||||||
e := db.GetMysqlClient().Query2(query,&usersinfo)
|
|
||||||
if e != nil{
|
|
||||||
log.Println(e.Error())
|
|
||||||
}
|
|
||||||
respdata["rows"] = usersinfo
|
|
||||||
respdata["total"] = len(usersinfo)
|
|
||||||
respdata["page"] = page
|
|
||||||
respdata["pageSize"] = pageSize
|
|
||||||
}
|
|
||||||
resp.Msg = "OK"
|
resp.Msg = "OK"
|
||||||
resp.Data = respdata
|
resp.Data = dat
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetUsers godoc
|
||||||
|
// @Summary GetUsers
|
||||||
|
// @Description Get all user with query
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Param page query int 1 "分页的页数"
|
||||||
|
// @Param pageSize query int 10 "name search by q"
|
||||||
|
// @Param displayname query string false "name search by q"
|
||||||
|
// @Param department_id query string false "name search by q"
|
||||||
|
// @Param permission_type query string false "name search by q"
|
||||||
|
// @Router /api/users [get]
|
||||||
|
func SerarchUsers(c *gin.Context) {
|
||||||
|
var statuscode int
|
||||||
|
var resp RespBase
|
||||||
|
|
||||||
|
resp.Msg = "获取失败"
|
||||||
|
resp.Status = 0
|
||||||
|
statuscode = 200
|
||||||
|
defer func() {
|
||||||
|
c.JSON(statuscode,resp)
|
||||||
|
}()
|
||||||
|
offset := c.Query("offset")
|
||||||
|
limit := c.Query("limit")
|
||||||
|
username := c.PostForm("username")
|
||||||
|
ioffset,e := strconv.Atoi(offset)
|
||||||
|
if nil != e{
|
||||||
|
logs.Error(e.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ilimit,er := strconv.Atoi(limit)
|
||||||
|
if nil != er{
|
||||||
|
logs.Error(e.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
dat := map[string] interface{}{}
|
||||||
|
users,all := model.GetUsers(int32(ilimit),int32(ioffset),username)
|
||||||
|
dat["users"] = users
|
||||||
|
dat["all"] = all
|
||||||
|
resp.Msg = "OK"
|
||||||
|
resp.Data = dat
|
||||||
|
}
|
||||||
func CreateVerify(length int32) string{
|
func CreateVerify(length int32) string{
|
||||||
strAry := []byte{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
|
strAry := []byte{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
|
||||||
result := string("")
|
result := string("")
|
||||||
|
@ -304,11 +286,9 @@ func Login(c *gin.Context) {
|
||||||
log.Println(err.Error())
|
log.Println(err.Error())
|
||||||
}
|
}
|
||||||
if req.RememberMe == 1{
|
if req.RememberMe == 1{
|
||||||
redis.Set(string(socketTokenMd5),string(sessionInfo),time.Second *2 * 24 * 3600 * 1000 )
|
config.RedisOne().Set(string(socketTokenMd5),string(sessionInfo),time.Second *2 * 24 * 3600 * 1000 )
|
||||||
|
|
||||||
}else {
|
}else {
|
||||||
redis.Set(string(socketTokenMd5),string(sessionInfo),time.Second *8 * 3600 * 1000 )
|
config.RedisOne().Set(string(socketTokenMd5),string(sessionInfo),time.Second *8 * 3600 * 1000 )
|
||||||
|
|
||||||
}
|
}
|
||||||
//存储session
|
//存储session
|
||||||
session := sessions.Get(c)
|
session := sessions.Get(c)
|
||||||
|
@ -331,11 +311,11 @@ func Login(c *gin.Context) {
|
||||||
resp.Status = 0
|
resp.Status = 0
|
||||||
resp.Data = string(sessionInfo)
|
resp.Data = string(sessionInfo)
|
||||||
}else {
|
}else {
|
||||||
statusCode = 422
|
resp.Status = 422
|
||||||
resp.Msg = "用户密码不正确"
|
resp.Msg = "用户密码不正确"
|
||||||
}
|
}
|
||||||
}else {
|
}else {
|
||||||
statusCode = 422
|
resp.Status = 422
|
||||||
resp.Msg = "登录账号不存在,请重新输入"
|
resp.Msg = "登录账号不存在,请重新输入"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -365,11 +345,10 @@ func Register(c *gin.Context) {
|
||||||
log.Println(e.Error())
|
log.Println(e.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
userKey := fmt.Sprintf("user_%s_verify",req.EmailAdress)
|
||||||
|
verify := config.RedisOne().Get(userKey).Val()
|
||||||
|
|
||||||
session := sessions.Get(c)
|
if verify != req.EmailCode{
|
||||||
email_code := session.Get(req.EmailAdress)
|
|
||||||
|
|
||||||
if email_code != req.EmailCode{
|
|
||||||
resp.Msg = "验证码错误"
|
resp.Msg = "验证码错误"
|
||||||
resp.Status = 20
|
resp.Status = 20
|
||||||
return
|
return
|
||||||
|
@ -384,13 +363,26 @@ func Register(c *gin.Context) {
|
||||||
passwdmd5 := h.Sum(nil)
|
passwdmd5 := h.Sum(nil)
|
||||||
strpassmd5 := ByteSliceToString(passwdmd5)
|
strpassmd5 := ByteSliceToString(passwdmd5)
|
||||||
user.UserPwd = strpassmd5
|
user.UserPwd = strpassmd5
|
||||||
user.UpdatedDate = time.Now().String()
|
user.UpdatedDate = time.Now().Format("2006-01-02 15:04:05")
|
||||||
user.CreatedDate = time.Now().String()
|
user.CreatedDate = time.Now().Format("2006-01-02 15:04:05")
|
||||||
|
|
||||||
n,er := db.GetMysqlClient().Insert("insert into users(user_name,user_pwd,created_date," +
|
var result []model.Users
|
||||||
"updated_date,display_name,email_address) values (?,?,?,?,?,?)",
|
|
||||||
user.UserName,user.UserPwd,user.CreatedDate,user.UpdatedDate,
|
er := db.GetMysqlClient().Query2("select * from users where user_name = ?",
|
||||||
|
&result,req.UserName)
|
||||||
|
if nil != er{
|
||||||
|
log.Println(er.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(result) > 0{
|
||||||
|
resp.Msg = "失败,账号已经存在"
|
||||||
|
resp.Status = 20
|
||||||
|
return
|
||||||
|
}
|
||||||
|
query := fmt.Sprintf("insert into users(user_name,user_pwd,created_date," +
|
||||||
|
"updated_date,display_name,email_address) values ('%s','%s','%s','%s','%s','%s') ",user.UserName,user.UserPwd,user.CreatedDate,user.UpdatedDate,
|
||||||
user.DisplayName,user.EmailAddress)
|
user.DisplayName,user.EmailAddress)
|
||||||
|
n,er := db.GetMysqlClient().Insert(query)
|
||||||
if n == 0 || n < 0{
|
if n == 0 || n < 0{
|
||||||
statusCode = 422
|
statusCode = 422
|
||||||
logs.Error(er.Error())
|
logs.Error(er.Error())
|
||||||
|
|
|
@ -16,6 +16,7 @@ import (
|
||||||
"time"
|
"time"
|
||||||
"user/controller"
|
"user/controller"
|
||||||
"user/config"
|
"user/config"
|
||||||
|
"user/db"
|
||||||
)
|
)
|
||||||
|
|
||||||
type RespJson struct {
|
type RespJson struct {
|
||||||
|
@ -62,9 +63,7 @@ type ReqSendEmailTpl struct {
|
||||||
Generate bool `json:"generate"`
|
Generate bool `json:"generate"`
|
||||||
}
|
}
|
||||||
type ReqSendEmail struct {
|
type ReqSendEmail struct {
|
||||||
Id int `json:"id"`
|
Email string `json:"email_address"`
|
||||||
From string `json:"from"`
|
|
||||||
To string `json:"to"`
|
|
||||||
Content string `json:"content"`
|
Content string `json:"content"`
|
||||||
}
|
}
|
||||||
func SendToMail(title, user, password, host, to, content string) error {
|
func SendToMail(title, user, password, host, to, content string) error {
|
||||||
|
@ -249,6 +248,20 @@ func OnSendEmailCode(c *gin.Context) {
|
||||||
resp.Msg = "ParaErr"
|
resp.Msg = "ParaErr"
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if req.Email != ""{
|
||||||
|
type Count struct {
|
||||||
|
Count int32 `json:"count"`
|
||||||
|
}
|
||||||
|
cnt := []Count{}
|
||||||
|
query := fmt.Sprintf("select count(*) as count from users where users.email_address = %s",req.Email)
|
||||||
|
e := db.GetMysqlClient().Query2(query,&cnt)
|
||||||
|
if nil !=e {
|
||||||
|
log.Println(e.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}else {
|
||||||
|
return
|
||||||
|
}
|
||||||
user := "c7458969@163.com"
|
user := "c7458969@163.com"
|
||||||
password := "caiyu123"
|
password := "caiyu123"
|
||||||
host := "smtp.163.com:25"
|
host := "smtp.163.com:25"
|
||||||
|
@ -257,9 +270,9 @@ func OnSendEmailCode(c *gin.Context) {
|
||||||
//发送
|
//发送
|
||||||
verCode := controller.CreateVerify(6)
|
verCode := controller.CreateVerify(6)
|
||||||
content := "您的验证码是" + verCode
|
content := "您的验证码是" + verCode
|
||||||
userKey := fmt.Sprintf("user_%d_verify",req.Id)
|
userKey := fmt.Sprintf("user_%s_verify",req.Email)
|
||||||
config.RedisOne().Set(userKey,verCode,time.Hour * 24)
|
config.RedisOne().Set(userKey,verCode,time.Hour * 24)
|
||||||
e = SendToMail("后台管理系统验证码", user, password, host, req.To, content)
|
e = SendToMail("后台管理系统验证码", user, password, host, req.Email, content)
|
||||||
if nil != e {
|
if nil != e {
|
||||||
log.Println(e.Error())
|
log.Println(e.Error())
|
||||||
resp.Msg = "Error"
|
resp.Msg = "Error"
|
||||||
|
|
25
main.go
25
main.go
|
@ -7,6 +7,7 @@ import (
|
||||||
"strconv"
|
"strconv"
|
||||||
"user/controller"
|
"user/controller"
|
||||||
"user/config"
|
"user/config"
|
||||||
|
"user/controller/mail"
|
||||||
"user/db"
|
"user/db"
|
||||||
"user/logs"
|
"user/logs"
|
||||||
)
|
)
|
||||||
|
@ -19,6 +20,23 @@ func InitMysql() {
|
||||||
db.Init()
|
db.Init()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
func CORSMiddleware(c *gin.Context) {
|
||||||
|
ori := c.Request.Header.Get("Origin")
|
||||||
|
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
|
||||||
|
c.Writer.Header().Set("Access-Control-Allow-Origin",ori)
|
||||||
|
log.Println(c.Request.Header.Get("Origin"))
|
||||||
|
c.Writer.Header().Set("Access-Control-Max-Age", "86400")
|
||||||
|
c.Writer.Header().Set("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding, x-access-token")
|
||||||
|
c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length")
|
||||||
|
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
|
||||||
|
|
||||||
|
if c.Request.Method == "OPTIONS" {
|
||||||
|
log.Println("OPTIONS")
|
||||||
|
c.AbortWithStatus(200)
|
||||||
|
} else {
|
||||||
|
c.Next()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
e := config.Init("user.yaml")
|
e := config.Init("user.yaml")
|
||||||
|
@ -35,6 +53,7 @@ func main() {
|
||||||
r := gin.Default()
|
r := gin.Default()
|
||||||
store := sessions.NewCookieStore([]byte("secret123"))
|
store := sessions.NewCookieStore([]byte("secret123"))
|
||||||
r.Use(sessions.Middleware("my_session", store))
|
r.Use(sessions.Middleware("my_session", store))
|
||||||
|
r.Use(CORSMiddleware)
|
||||||
{
|
{
|
||||||
/** 添加或修改用户 **/
|
/** 添加或修改用户 **/
|
||||||
r.POST("/api/user", controller.SetUser)
|
r.POST("/api/user", controller.SetUser)
|
||||||
|
@ -43,15 +62,15 @@ func main() {
|
||||||
/** 获取单独用户详情信息 methods(id) **/
|
/** 获取单独用户详情信息 methods(id) **/
|
||||||
r.GET("/api/user", controller.GetUser)
|
r.GET("/api/user", controller.GetUser)
|
||||||
/** 获取所有用户 **/
|
/** 获取所有用户 **/
|
||||||
r.GET("/api/users", controller.GetUsers)
|
r.GET("/api/users", controller.Users)
|
||||||
|
r.POST("/api/search_users", controller.SerarchUsers)
|
||||||
/** 用户登录 **/
|
/** 用户登录 **/
|
||||||
r.POST("/api/login", controller.Login)
|
r.POST("/api/login", controller.Login)
|
||||||
/** 用户注册 **/
|
/** 用户注册 **/
|
||||||
r.POST("/api/register", controller.Register)
|
r.POST("/api/register", controller.Register)
|
||||||
/** 用户退出登陆 **/
|
/** 用户退出登陆 **/
|
||||||
r.GET("/api/logout", controller.Logout)
|
r.GET("/api/logout", controller.Logout)
|
||||||
|
r.POST("/api/verify",mail.OnSendEmailCode)
|
||||||
r.POST("/api/email_code",controller.SendEmailCode)
|
|
||||||
}
|
}
|
||||||
r.Run(":" + strconv.Itoa(config.GetPort()))
|
r.Run(":" + strconv.Itoa(config.GetPort()))
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,13 +1,48 @@
|
||||||
package model
|
package model
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"qiniupkg.com/x/log.v7"
|
||||||
|
"user/db"
|
||||||
|
"user/logs"
|
||||||
|
)
|
||||||
|
|
||||||
type Users struct {
|
type Users struct {
|
||||||
ID int64 `sql:"id" json:"id"`
|
ID int64 `sql:"id" json:"id"`
|
||||||
UserName string `sql:"user_name" json:"UserName"`
|
UserName string `sql:"user_name" json:"user_name"`
|
||||||
UserPwd string `sql:"user_pwd" json:"UserPwd"`
|
UserPwd string `sql:"user_pwd" json:"-"`
|
||||||
CreatedDate string `sql:"created_date" json:"CreatedDate"`
|
CreatedDate string `sql:"created_date" json:"created_date"`
|
||||||
UpdatedDate string `sql:"updated_date" json:"UpdatedDate"`
|
UpdatedDate string `sql:"updated_date" json:"updated_date"`
|
||||||
DisplayName string `sql:"display_name" json:"DisplayName"`
|
DisplayName string `sql:"display_name" json:"display_name"`
|
||||||
EmailAddress string `sql:"email_address" json:"EmailAddress"`
|
EmailAddress string `sql:"email_address" json:"email_address"`
|
||||||
Tel string `sql:"tel" json:"tel"`
|
Tel string `sql:"tel" json:"tel"`
|
||||||
Avatar string `sql:"avatar" json:"Avatar"`
|
Avatar string `sql:"avatar" json:"avatar"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func GetUsers(limit int32,offsetPage int32,name string) ([]Users,int32){
|
||||||
|
users := []Users{}
|
||||||
|
var query string
|
||||||
|
if name != ""{
|
||||||
|
log.Println(name)
|
||||||
|
query = fmt.Sprintf("select * from users where user_name like '%s' limit %d offset %d","%%" + name + "%%",limit,offsetPage*limit)
|
||||||
|
log.Printf(query)
|
||||||
|
}else {
|
||||||
|
query = fmt.Sprintf("select * from users limit %d offset %d",limit,offsetPage*limit)
|
||||||
|
}
|
||||||
|
err := db.GetMysqlClient().Query2(query,&users)
|
||||||
|
if nil != err{
|
||||||
|
logs.Error(err.Error())
|
||||||
|
}
|
||||||
|
type Count struct {
|
||||||
|
Count int32 `sql:"count"`
|
||||||
|
}
|
||||||
|
cnts := []Count{}
|
||||||
|
query = fmt.Sprintf("select count(*) as count from users")
|
||||||
|
err = db.GetMysqlClient().Query2(query,&cnts)
|
||||||
|
if nil != err{
|
||||||
|
logs.Error(err.Error())
|
||||||
|
}
|
||||||
|
return users,cnts[0].Count
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,98 @@
|
||||||
|
// Copyright 2016 The Go Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
// +build ignore
|
||||||
|
|
||||||
|
// mkpost processes the output of cgo -godefs to
|
||||||
|
// modify the generated types. It is used to clean up
|
||||||
|
// the sys API in an architecture specific manner.
|
||||||
|
//
|
||||||
|
// mkpost is run after cgo -godefs; see README.md.
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"fmt"
|
||||||
|
"go/format"
|
||||||
|
"io/ioutil"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"regexp"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// Get the OS and architecture (using GOARCH_TARGET if it exists)
|
||||||
|
goos := os.Getenv("GOOS")
|
||||||
|
goarch := os.Getenv("GOARCH_TARGET")
|
||||||
|
if goarch == "" {
|
||||||
|
goarch = os.Getenv("GOARCH")
|
||||||
|
}
|
||||||
|
// Check that we are using the new build system if we should be.
|
||||||
|
if goos == "linux" && goarch != "sparc64" {
|
||||||
|
if os.Getenv("GOLANG_SYS_BUILD") != "docker" {
|
||||||
|
os.Stderr.WriteString("In the new build system, mkpost should not be called directly.\n")
|
||||||
|
os.Stderr.WriteString("See README.md\n")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
b, err := ioutil.ReadAll(os.Stdin)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Intentionally export __val fields in Fsid and Sigset_t
|
||||||
|
valRegex := regexp.MustCompile(`type (Fsid|Sigset_t) struct {(\s+)X__val(\s+\S+\s+)}`)
|
||||||
|
b = valRegex.ReplaceAll(b, []byte("type $1 struct {${2}Val$3}"))
|
||||||
|
|
||||||
|
// If we have empty Ptrace structs, we should delete them. Only s390x emits
|
||||||
|
// nonempty Ptrace structs.
|
||||||
|
ptraceRexexp := regexp.MustCompile(`type Ptrace((Psw|Fpregs|Per) struct {\s*})`)
|
||||||
|
b = ptraceRexexp.ReplaceAll(b, nil)
|
||||||
|
|
||||||
|
// Replace the control_regs union with a blank identifier for now.
|
||||||
|
controlRegsRegex := regexp.MustCompile(`(Control_regs)\s+\[0\]uint64`)
|
||||||
|
b = controlRegsRegex.ReplaceAll(b, []byte("_ [0]uint64"))
|
||||||
|
|
||||||
|
// Remove fields that are added by glibc
|
||||||
|
// Note that this is unstable as the identifers are private.
|
||||||
|
removeFieldsRegex := regexp.MustCompile(`X__glibc\S*`)
|
||||||
|
b = removeFieldsRegex.ReplaceAll(b, []byte("_"))
|
||||||
|
|
||||||
|
// Convert [65]int8 to [65]byte in Utsname members to simplify
|
||||||
|
// conversion to string; see golang.org/issue/20753
|
||||||
|
convertUtsnameRegex := regexp.MustCompile(`((Sys|Node|Domain)name|Release|Version|Machine)(\s+)\[(\d+)\]u?int8`)
|
||||||
|
b = convertUtsnameRegex.ReplaceAll(b, []byte("$1$3[$4]byte"))
|
||||||
|
|
||||||
|
// Remove spare fields (e.g. in Statx_t)
|
||||||
|
spareFieldsRegex := regexp.MustCompile(`X__spare\S*`)
|
||||||
|
b = spareFieldsRegex.ReplaceAll(b, []byte("_"))
|
||||||
|
|
||||||
|
// Remove cgo padding fields
|
||||||
|
removePaddingFieldsRegex := regexp.MustCompile(`Pad_cgo_\d+`)
|
||||||
|
b = removePaddingFieldsRegex.ReplaceAll(b, []byte("_"))
|
||||||
|
|
||||||
|
// Remove padding, hidden, or unused fields
|
||||||
|
removeFieldsRegex = regexp.MustCompile(`\b(X_\S+|Padding)`)
|
||||||
|
b = removeFieldsRegex.ReplaceAll(b, []byte("_"))
|
||||||
|
|
||||||
|
// Remove the first line of warning from cgo
|
||||||
|
b = b[bytes.IndexByte(b, '\n')+1:]
|
||||||
|
// Modify the command in the header to include:
|
||||||
|
// mkpost, our own warning, and a build tag.
|
||||||
|
replacement := fmt.Sprintf(`$1 | go run mkpost.go
|
||||||
|
// Code generated by the command above; see README.md. DO NOT EDIT.
|
||||||
|
|
||||||
|
// +build %s,%s`, goarch, goos)
|
||||||
|
cgoCommandRegex := regexp.MustCompile(`(cgo -godefs .*)`)
|
||||||
|
b = cgoCommandRegex.ReplaceAll(b, []byte(replacement))
|
||||||
|
|
||||||
|
// gofmt
|
||||||
|
b, err = format.Source(b)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
os.Stdout.Write(b)
|
||||||
|
}
|
Loading…
Reference in New Issue