main.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "os"
  8. "time"
  9. "git.chuangxin1.com/csacred/toolkit"
  10. "git.chuangxin1.com/csacred/toolkit/example/cuser/service"
  11. khttp "git.chuangxin1.com/csacred/toolkit/http"
  12. "github.com/go-kit/kit/log"
  13. )
  14. func main() {
  15. var addr = flag.String("listen", ":9122", "Address for HTTP server")
  16. logger := log.NewLogfmtLogger(os.Stderr)
  17. flag.Parse()
  18. readTimeout := 30 * time.Second
  19. writeTimeout := 30 * time.Second
  20. maxHeaderBytes := 1 << 20
  21. router := khttp.NewRouter()
  22. khttp.AddGetHandle(router, "/ver", func(w http.ResponseWriter, r *http.Request) {
  23. ver := map[string]string{
  24. "version": "0.2.0",
  25. "comments": "chuangxin1.com API",
  26. "author": "ls"}
  27. khttp.WriteJSON(w, toolkit.RowReplyData(ver))
  28. })
  29. khttp.AddPostHandle(router, "/upload", func(w http.ResponseWriter, r *http.Request) {
  30. defer r.Body.Close()
  31. body, _ := ioutil.ReadAll(r.Body)
  32. fmt.Println(string(body))
  33. khttp.WriteJSON(w, toolkit.OkReplyData())
  34. })
  35. dns := fmt.Sprintf(
  36. "root:Lsar-5211@tcp(127.0.0.1:3306)/community_user?charset=utf8mb4")
  37. dbConfig := toolkit.DbConfig{
  38. Driver: `mysql`,
  39. DNS: dns,
  40. MaxOpenConns: 50,
  41. MaxIdle: 5,
  42. MaxLifetime: 0}
  43. toolkit.SetDbConfig(dbConfig)
  44. defer toolkit.FreeDB()
  45. srv := service.New()
  46. handers := service.GenServiceHandler(srv, logger)
  47. for i := range handers {
  48. fmt.Println(handers[i].Method, handers[i].Router)
  49. router.Handler(handers[i].Method, handers[i].Router, handers[i].Hander)
  50. }
  51. //serviceRouter(router, logger)
  52. //hs := make(HostSwitch)
  53. //hs["192.168.1.8:9122"] = router
  54. //toolkit.StartServer(addr, hs, readTimeout, writeTimeout, maxHeaderBytes, logger)
  55. khttp.ListenAndServe(
  56. *addr,
  57. router,
  58. readTimeout,
  59. writeTimeout,
  60. maxHeaderBytes,
  61. logger)
  62. }