Instantly share code, notes, and snippets.

Embed
What would you like to do?
package apps
import (
"encoding/json"
"github.com/astaxie/beego/validation"
"github.com/gorilla/mux"
"io/ioutil"
"log"
"net/http"
"strconv"
)
type UserRes struct {
Message string `json:"message"`
ErrorCode int `json:"error_code"`
}
type ErrUser struct {
Name string `json:"name"`
Message string `json:"message"`
ErrorCode int64 `json:"error_code"`
}
// 用户列表
func userList(w http.ResponseWriter, r *http.Request) {
var users []User
data := db.Find(&users)
json.NewEncoder(w).Encode(data)
}
// 新增用户
func userAdd(w http.ResponseWriter, r *http.Request) {
var (
data []byte
body *User
)
data, _ = ioutil.ReadAll(r.Body)
if err := json.Unmarshal(data, &body); err != nil {
panic(err)
}
valid := validation.Validation{}
users := User{Username: body.Username, Password: body.Password, Email: body.Email, Phone: body.Phone}
b, err := valid.Valid(&users)
if err != nil {
panic(err.Error())
}
if !b {
for _, err := range valid.Errors {
errMsg := &ErrUser{
Name: err.Field,
Message: err.Message,
ErrorCode: 10005,
}
json.NewEncoder(w).Encode(errMsg)
}
return
}
db.NewRecord(users) // => 主键为空返回`true`
db.Create(&users)
db.NewRecord(users) // => 创建`user`后返回`false`
resp := &UserRes{
Message: "创建用户成功!",
ErrorCode: 0,
}
json.NewEncoder(w).Encode(resp)
}
// 删除用户
func userDelete(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
db.Delete(&User{}, vars["id"])
resp := &UserRes{
Message: "删除用户成功!",
ErrorCode: 0,
}
json.NewEncoder(w).Encode(resp)
}
func InitApiServer() {
myRouter := mux.NewRouter().StrictSlash(true)
myRouter.HandleFunc("/", userList).Methods("GET")
myRouter.HandleFunc("/user/add", userAdd).Methods("POST")
myRouter.HandleFunc("/user/delete/{id}", userDelete).Methods("DELETE")
log.Fatal(http.ListenAndServe(":"+strconv.Itoa(C.ApiPort), myRouter))
return
}
package apps
import (
"encoding/json"
"io/ioutil"
)
type Config struct {
ApiPort int `json:"api_port"`
DbUri string `json:"db_uri"`
}
var (
// 外部可以引入配置
C *Config
)
func InitConfig(filename string) (err error) {
var (
content []byte
conf Config
)
// 读取配置文件
if content, err = ioutil.ReadFile(filename); err != nil {
panic(err)
}
// Json反序列化
if err = json.Unmarshal(content, &conf); err != nil {
panic(err)
}
C = &conf
return
}
package apps
import (
_ "github.com/astaxie/beego/validation"
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
var (
db *gorm.DB
err error
)
type User struct {
gorm.Model
Username string `valid:"Required"`
Password string `valid:"Required"`
Email string `valid:"Email;MaxSize(100)"`
Phone string `valid:"Mobile"`
}
var (
MUser *User
)
func MysqlConnect() {
var (
users User
)
if db, err = gorm.Open("mysql", C.DbUri); err != nil {
panic("数据库连接失败!")
}
MUser = &users
return
}
{
"api_port": 8081,
"db_uri": "root:leto123456@(192.168.3.30:3307)/go?parseTime=True"
}
package main
import (
"awesomeProject/gshell/master/apps"
"flag"
"fmt"
"runtime"
)
var (
confFile string
)
func initArgs() {
// 解析命令行命令
flag.StringVar(&confFile, "config", "../config/g_shell.json", "指定master路径")
flag.Parse()
}
func initEnv() {
// 初始化线程
runtime.GOMAXPROCS(runtime.NumCPU())
}
func main() {
var (
err error
)
// 初始化命令行参数
initArgs()
// 初始化线程
initEnv()
if err = apps.InitConfig(confFile); err != nil {
goto ERR
}
// 初始化数据库
apps.MysqlConnect()
// 初始化服务
apps.InitApiServer()
return
ERR:
fmt.Println(err)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment