Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

84 linhas
1.9KB

  1. package main
  2. import (
  3. "biukop/sfm/loan"
  4. "encoding/json"
  5. "fmt"
  6. log "github.com/sirupsen/logrus"
  7. "net/http"
  8. "net/http/httputil"
  9. "strings"
  10. )
  11. type httpEntry func(http.ResponseWriter, *http.Request)
  12. var httpEntryMap = map[string]httpEntry{
  13. apiV1Prefix: apiV1Main,
  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. setupRootFileServer()
  24. //always the last one
  25. setupHTTPHandler()
  26. }
  27. func setupRootFileServer() {
  28. //root of doc
  29. for idx, node := range config.Static {
  30. log.Printf("setting up static %d with %+v\n", idx, node)
  31. fs := http.FileServer(http.Dir(node.Dir))
  32. http.Handle(node.StaticUrl, http.StripPrefix(node.StripPrefix, fs))
  33. }
  34. }
  35. func setupHTTPHandler() {
  36. for key, val := range httpEntryMap {
  37. http.HandleFunc(key, val)
  38. }
  39. log.Printf("Server started at %s:%s\n", config.Host, config.Port)
  40. log.Fatal(http.ListenAndServe(config.Host+":"+config.Port, nil))
  41. }
  42. func dummyHandler(w http.ResponseWriter, r *http.Request) {
  43. p := loan.People{}
  44. p.FakeNew()
  45. fmt.Fprintf(w, "Hello, there %s, %+v\n", loan.Version, p)
  46. }
  47. func apiSendJson(p interface{}, w http.ResponseWriter) {
  48. b, e := json.Marshal(p)
  49. w.Header().Set("Content-Type", "text/json; charset=utf-8")
  50. if e == nil {
  51. fmt.Fprint(w, string(b))
  52. } else {
  53. apiV1DumpRequest(w, nil, nil)
  54. }
  55. }
  56. func apiV1DumpRequest(w http.ResponseWriter, r *http.Request, ss *loan.Session) {
  57. dump := logRequestDebug(httputil.DumpRequest(r, true))
  58. dump = strings.TrimSpace(dump)
  59. msg := fmt.Sprintf("Unhandled Protocol = %s path= %s", r.Method, r.URL.Path)
  60. dumpLines := strings.Split(dump, "\r\n")
  61. ar := apiV1ResponseBlank()
  62. ar.Env.Msg = msg
  63. ar.Env.Session = *ss
  64. ar.Env.Session.Secret = "***********"
  65. ar.add("Body", dumpLines)
  66. b, _ := ar.toJson()
  67. fmt.Fprintf(w, "%s\n", b)
  68. }