You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
1.8KB

  1. package main
  2. import (
  3. "biukop.com/sfm/loan"
  4. "encoding/gob"
  5. "encoding/json"
  6. "fmt"
  7. log "github.com/sirupsen/logrus"
  8. "net/http"
  9. )
  10. type httpEntry func(http.ResponseWriter, *http.Request)
  11. var httpEntryMap = map[string]httpEntry{
  12. apiV1Prefix: apiV1Main,
  13. apiV1WebSocket: apiV1WebSocketHandler,
  14. "/dummy/": dummyHandler,
  15. }
  16. func main() {
  17. err := config.readConfig() //wechat API config
  18. if err != nil {
  19. log.Println(err)
  20. log.Fatalf("unable to read %s, program quit\n", configFile)
  21. return
  22. }
  23. loan.SetDSN(config.DSN)
  24. setupRootFileServer()
  25. //always the last one
  26. setupHTTPHandler()
  27. }
  28. func init() {
  29. gob.Register(loginForm{})
  30. customFormatter := new(log.TextFormatter)
  31. customFormatter.TimestampFormat = "2006-01-02 15:04:05"
  32. log.SetFormatter(customFormatter)
  33. log.Info("Change Log Format before FullTimestamp=true")
  34. customFormatter.FullTimestamp = true
  35. }
  36. func setupRootFileServer() {
  37. //root of doc
  38. for idx, node := range config.Static {
  39. log.Printf("setting up static %d with %+v\n", idx, node)
  40. fs := http.FileServer(http.Dir(node.Dir))
  41. http.Handle(node.StaticUrl, http.StripPrefix(node.StripPrefix, fs))
  42. }
  43. }
  44. func setupHTTPHandler() {
  45. for key, val := range httpEntryMap {
  46. http.HandleFunc(key, val)
  47. }
  48. log.Printf("Server started at %s:%s\n", config.Host, config.Port)
  49. //log.Fatal(http.ListenAndServe(config.Host+":"+config.Port, nil))
  50. log.Fatal(http.ListenAndServeTLS(config.Host+":"+config.Port, config.TlsCert, config.TlsKey, nil))
  51. }
  52. func dummyHandler(w http.ResponseWriter, r *http.Request) {
  53. p := loan.People{}
  54. p.FakeNew()
  55. fmt.Fprintf(w, "Hello, there %s, %+v\n", loan.Version, p)
  56. }
  57. func apiSendJson(p interface{}, w http.ResponseWriter) {
  58. b, e := json.Marshal(p)
  59. w.Header().Set("Content-Type", "text/json; charset=utf-8")
  60. if e == nil {
  61. fmt.Fprint(w, string(b))
  62. } else {
  63. apiV1DumpRequest(w, nil, nil)
  64. }
  65. }