httpserver.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. package main
  2. import (
  3. "bytes"
  4. "fmt"
  5. "net/http"
  6. "os"
  7. "time"
  8. "git.chuangxin1.com/csacred/toolkit"
  9. "git.chuangxin1.com/csacred/toolkit/binding"
  10. khttp "git.chuangxin1.com/csacred/toolkit/http"
  11. "github.com/chuangxin1/toolkit/types"
  12. "github.com/go-kit/kit/log"
  13. )
  14. // FormID http request from of user
  15. type FormID struct {
  16. ID int `json:"id" db:"id" form:"id"`
  17. }
  18. // FormUser http request from of user
  19. type FormUser struct {
  20. Page int `json:"page" db:"page" form:"page" validate:"required,gt=0"`
  21. PageSize int `json:"pagesize" db:"pagesize" form:"pagesize" validate:"required,gte=5,lte=100"`
  22. Code int `json:"code" db:"code" form:"code"`
  23. Name string `json:"name" db:"name" form:"name" validate:"max=20"`
  24. ID int `json:"id" db:"id" form:"id"`
  25. }
  26. // User user
  27. type User struct {
  28. ID int `json:"id"`
  29. Phone string `json:"phone"`
  30. Name string `json:"name"`
  31. Passwd string `json:"passwd"`
  32. Sex string `json:"sex"`
  33. Birthday types.DateText `json:"birthday"`
  34. //*
  35. Country types.NullInt `json:"country"`
  36. Province types.NullInt `json:"province"`
  37. City types.NullInt `json:"city"`
  38. Nation types.NullInt `json:"nation"`
  39. // */
  40. Avatar types.NullString `json:"avatar"`
  41. Signature types.NullString `json:"signature"`
  42. Category int `json:"category"`
  43. Scale int `json:"scale"`
  44. Score int `json:"score"`
  45. Balance float32 `json:"balance"`
  46. Status int `json:"status"`
  47. Stime string `json:"stime"`
  48. Attr types.JSONText `json:"attr"`
  49. }
  50. func get(u FormID) (user User, err error) {
  51. var db = toolkit.NewDB()
  52. //if err = db.Connect(); err == nil {
  53. //defer db.Close()
  54. var (
  55. buffer bytes.Buffer
  56. where bytes.Buffer
  57. )
  58. buffer.WriteString(`select id, phone, name, password passwd, sex, `)
  59. buffer.WriteString(`birthday, country, province, city, nation, avatar, `)
  60. buffer.WriteString(`signature, category, balance, scale, score, attr, `)
  61. buffer.WriteString(`status, sys_time stime from usr_user`)
  62. where.WriteString(` where id > 0 and id = :id`)
  63. buffer.WriteString(where.String())
  64. err = db.Row(&user, buffer.String(), u)
  65. //}
  66. return
  67. }
  68. func list(formUser FormUser) (users []User, total int, err error) {
  69. var db = toolkit.NewDB()
  70. //if err = db.Connect(); err == nil {
  71. //defer db.Close()
  72. var (
  73. buffer bytes.Buffer
  74. where bytes.Buffer
  75. sql bytes.Buffer
  76. )
  77. buffer.WriteString(`select id, phone, name, password passwd, sex, `)
  78. buffer.WriteString(`birthday, country, province, city, nation, avatar, `)
  79. buffer.WriteString(`signature, category, balance, scale, score, attr, `)
  80. buffer.WriteString(`status, sys_time stime `)
  81. where.WriteString(` from usr_user where id > 0`)
  82. if len(formUser.Name) > 0 {
  83. where.WriteString(` and name like :name`)
  84. }
  85. sql.WriteString(`select count(*) total`)
  86. sql.WriteString(where.String())
  87. buffer.WriteString(where.String())
  88. buffer.WriteString(` order by id desc`)
  89. buffer.WriteString(db.Limit(formUser.Page, formUser.PageSize))
  90. //fmt.Println(buffer.String(), sql.String())
  91. err = db.Row(&total, sql.String(), formUser)
  92. //fmt.Println("total", total)
  93. if err != nil {
  94. return
  95. }
  96. err = db.Rows(&users, buffer.String(), formUser)
  97. return
  98. }
  99. func main() {
  100. logger := log.NewLogfmtLogger(os.Stderr)
  101. readTimeout := 30 * time.Second
  102. writeTimeout := 30 * time.Second
  103. maxHeaderBytes := 1 << 20
  104. router := khttp.NewRouter()
  105. khttp.AddGetHandle(router, "/ver", func(w http.ResponseWriter, r *http.Request) {
  106. ver := map[string]string{
  107. "version": "0.2.0",
  108. "comments": "chuangxin1.com API",
  109. "author": "ls"}
  110. khttp.WriteJSON(w, toolkit.RowReplyData(ver))
  111. })
  112. khttp.AddGetHandle(router, "/users", func(w http.ResponseWriter, r *http.Request) {
  113. var user FormUser
  114. user.Page = 1
  115. user.PageSize = 20
  116. users, total, err := list(user)
  117. if err != nil {
  118. khttp.WriteJSON(w, toolkit.ErrReplyData(toolkit.ErrDataNotFound, err.Error()))
  119. return
  120. }
  121. khttp.WriteJSON(w, toolkit.RowsReplyData(total, users))
  122. })
  123. khttp.AddGetHandle(router, "/profile", func(w http.ResponseWriter, r *http.Request) {
  124. var user FormID
  125. binding.Bind(r, &user)
  126. users, err := get(user)
  127. if err != nil {
  128. khttp.WriteJSON(w, toolkit.ErrReplyData(toolkit.ErrDataNotFound, err.Error()))
  129. return
  130. }
  131. khttp.WriteJSON(w, toolkit.RowReplyData(users))
  132. })
  133. dns := fmt.Sprintf(
  134. "root:Lsar-5211@tcp(127.0.0.1:3306)/community_user?charset=utf8mb4")
  135. dbConfig := toolkit.DbConfig{
  136. Driver: `mysql`,
  137. DNS: dns,
  138. MaxOpenConns: 50,
  139. MaxIdle: 5,
  140. MaxLifetime: 0}
  141. toolkit.SetDbConfig(dbConfig)
  142. defer toolkit.FreeDB()
  143. //serviceRouter(router, logger)
  144. //hs := make(HostSwitch)
  145. //hs["192.168.1.8:9122"] = router
  146. //toolkit.StartServer(addr, hs, readTimeout, writeTimeout, maxHeaderBytes, logger)
  147. khttp.ListenAndServe(
  148. ":9006",
  149. router,
  150. readTimeout,
  151. writeTimeout,
  152. maxHeaderBytes,
  153. logger)
  154. }