package main import ( "biukop/sfm/loan" "encoding/json" "fmt" log "github.com/sirupsen/logrus" "net/http" "net/http/httputil" "strings" ) type httpEntry func(http.ResponseWriter, *http.Request) var httpEntryMap = map[string]httpEntry{ apiV1Prefix: apiV1Main, "/dummy/": dummyHandler, } func main() { err := config.readConfig() //wechat API config if err != nil { log.Println(err) log.Fatalf("unable to read %s, program quit\n", configFile) return } setupRootFileServer() //always the last one setupHTTPHandler() } func setupRootFileServer() { //root of doc for idx, node := range config.Static { log.Printf("setting up static %d with %+v\n", idx, node) fs := http.FileServer(http.Dir(node.Dir)) http.Handle(node.StaticUrl, http.StripPrefix(node.StripPrefix, fs)) } } func setupHTTPHandler() { for key, val := range httpEntryMap { http.HandleFunc(key, val) } log.Printf("Server started at %s:%s\n", config.Host, config.Port) log.Fatal(http.ListenAndServe(config.Host+":"+config.Port, nil)) } func dummyHandler(w http.ResponseWriter, r *http.Request) { p := loan.People{} p.FakeNew() fmt.Fprintf(w, "Hello, there %s, %+v\n", loan.Version, p) } func apiSendJson(p interface{}, w http.ResponseWriter) { b, e := json.Marshal(p) w.Header().Set("Content-Type", "text/json; charset=utf-8") if e == nil { fmt.Fprint(w, string(b)) } else { apiV1DumpRequest(w, nil, nil) } } func apiV1DumpRequest(w http.ResponseWriter, r *http.Request, ss *loan.Session) { dump := logRequestDebug(httputil.DumpRequest(r, true)) dump = strings.TrimSpace(dump) msg := fmt.Sprintf("Unhandled Protocol = %s path= %s", r.Method, r.URL.Path) dumpLines := strings.Split(dump, "\r\n") ar := apiV1ResponseBlank() ar.Env.Msg = msg ar.Env.Session = *ss ar.Env.Session.Bin = []byte("masked data") //clear ar.Env.Session.Secret = "***********" ar.add("Body", dumpLines) ar.add("mid", ss.Get("mid")) b, _ := ar.toJson() fmt.Fprintf(w, "%s\n", b) }