server.go 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. package web
  2. import (
  3. "context"
  4. "encoding/json"
  5. "encoding/xml"
  6. "fmt"
  7. "log"
  8. "net/http"
  9. "os"
  10. "os/signal"
  11. "syscall"
  12. "time"
  13. "git.chuangxin1.com/cx/tyr"
  14. )
  15. func header(w http.ResponseWriter, contentType string) {
  16. w.Header().Set(`Content-Type`, contentType)
  17. w.Header().Set(`X-Powered-By`, tyr.LibName+`/`+tyr.LibVersion)
  18. w.WriteHeader(http.StatusOK)
  19. }
  20. // Redirect redirect
  21. func Redirect(w http.ResponseWriter, url string) {
  22. w.Header().Set(`Location`, url)
  23. w.WriteHeader(http.StatusFound)
  24. }
  25. // GetRealIP get real IP from Request
  26. func GetRealIP(req *http.Request) (ip string) {
  27. if ips := req.Header["X-Real-Ip"]; ips != nil {
  28. ip = ips[0]
  29. }
  30. return
  31. }
  32. // SetCookie set http cookie
  33. func SetCookie(w http.ResponseWriter, name, value, path string, maxAge int) {
  34. cookie := &http.Cookie{
  35. Name: name,
  36. Value: value,
  37. Path: path,
  38. HttpOnly: false,
  39. MaxAge: maxAge}
  40. http.SetCookie(w, cookie)
  41. }
  42. // WriteJSON response JSON data.
  43. func WriteJSON(w http.ResponseWriter, response interface{}) error {
  44. header(w, `application/json; charset=utf-8`)
  45. return json.NewEncoder(w).Encode(response)
  46. }
  47. // WriteXML response XML data.
  48. func WriteXML(w http.ResponseWriter, response interface{}) error {
  49. header(w, `application/xml; charset=utf-8`)
  50. return xml.NewEncoder(w).Encode(response)
  51. }
  52. // WriteBytes response bytes
  53. func WriteBytes(w http.ResponseWriter, response interface{}) error {
  54. header(w, `text/html; charset=utf-8`)
  55. w.Write(response.([]byte))
  56. return nil
  57. }
  58. // WriteCtxJSON response JSON data.
  59. func WriteCtxJSON(ctx context.Context, w http.ResponseWriter, response interface{}) error {
  60. return WriteJSON(w, response)
  61. }
  62. // WriteCtxXML response XML data.
  63. func WriteCtxXML(ctx context.Context, w http.ResponseWriter, response interface{}) error {
  64. return WriteXML(w, response)
  65. }
  66. // WriteCtxBytes response text data.
  67. func WriteCtxBytes(ctx context.Context, w http.ResponseWriter, response interface{}) error {
  68. return WriteBytes(w, response)
  69. }
  70. // ResponseJSON reply JSON
  71. func ResponseJSON(reply *tyr.ReplyData, req *http.Request, w http.ResponseWriter) error {
  72. return WriteJSON(w, reply)
  73. }
  74. func newServe(addr string, router http.Handler) *http.Server {
  75. return &http.Server{
  76. Addr: addr,
  77. Handler: router,
  78. ReadTimeout: 30 * time.Second,
  79. WriteTimeout: 30 * time.Second,
  80. MaxHeaderBytes: 1 << 20,
  81. }
  82. }
  83. // ListenAndServe new server and start
  84. func ListenAndServe(addr string, router http.Handler) {
  85. s := newServe(addr, router)
  86. errc := make(chan error)
  87. go func() {
  88. c := make(chan os.Signal)
  89. signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
  90. errc <- fmt.Errorf("%s", <-c)
  91. }()
  92. go func() {
  93. log.Println("HTTP Server listen on", addr)
  94. errc <- s.ListenAndServe()
  95. log.Println("Exit HTTP server", "Quit")
  96. }()
  97. log.Println("Exit", <-errc)
  98. }
  99. // ListenAndServeTLS new server and start
  100. func ListenAndServeTLS(addr, certFile, keyFile string, router http.Handler) {
  101. s := newServe(addr, router)
  102. errc := make(chan error)
  103. go func() {
  104. c := make(chan os.Signal)
  105. signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
  106. errc <- fmt.Errorf("%s", <-c)
  107. }()
  108. go func() {
  109. log.Println("HTTP Server listen on", addr)
  110. errc <- s.ListenAndServeTLS(certFile, keyFile)
  111. log.Println("Exit HTTP server", "Quit")
  112. }()
  113. log.Println("Exit", <-errc)
  114. }