From 573cf4f447947c9dc65822e86acd584d3cf1e380 Mon Sep 17 00:00:00 2001 From: fengxxc <744320491@qq.com> Date: Sat, 26 Nov 2022 14:08:32 +0800 Subject: [PATCH] feat(server): simple http server support --- main.go | 19 +++++++++++++++++-- server/server.go | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 2 deletions(-) create mode 100644 server/server.go diff --git a/main.go b/main.go index a92b3f1..b221de1 100644 --- a/main.go +++ b/main.go @@ -6,6 +6,7 @@ import ( "github.com/fengxxc/wechatmp2markdown/format" "github.com/fengxxc/wechatmp2markdown/parse" + "github.com/fengxxc/wechatmp2markdown/server" ) func main() { @@ -15,8 +16,22 @@ func main() { if len(args) <= 2 { panic("not enough args") } - url := args[1] - filename := args[2] + args1 := args[1] + args2 := args[2] + + if args1 == "server" { + // server pattern + port := args2 + if port == "" { + port = "8964" + } + server.Start(":" + port) + return + } + + // cli pattern + url := args1 + filename := args2 fmt.Printf("url: %s, filename: %s\n", url, filename) var articleStruct parse.Article = parse.ParseFromURL(url) format.FormatAndSave(articleStruct, filename) diff --git a/server/server.go b/server/server.go new file mode 100644 index 0000000..63ba743 --- /dev/null +++ b/server/server.go @@ -0,0 +1,33 @@ +package server + +import ( + "fmt" + "log" + "net/http" + + "github.com/fengxxc/wechatmp2markdown/format" + "github.com/fengxxc/wechatmp2markdown/parse" +) + +func Start(addr string) { + http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + wechatmpURL := r.FormValue("url") + if wechatmpURL == "" { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("param 'url' must not be empty. please put in a wechatmp URL and try again.")) + return + } + w.Header().Set("Content-Type", "application/octet-stream") + var articleStruct parse.Article = parse.ParseFromURL(wechatmpURL) + title := articleStruct.Title.Val.(string) + w.Header().Set("Content-Disposition", "attachment; filename="+title+".md") + var mdString string = format.Format(articleStruct) + w.Write([]byte(mdString)) + return + }) + + fmt.Printf("wechatmp2markdown server listening on %s\n", addr) + if err := http.ListenAndServe(addr, nil); err != nil { + log.Fatal(err) + } +}