package api import ( "blog/config" "encoding/json" "fmt" "net/http" "regexp" ) type MemoInfo struct { Id int `json:"id"` Name string `json:"name"` RowStatus string `json:"rowStatus"` CreatorId int `json:"creatorId"` CreatedTs int `json:"createdTs"` UpdatedTs int `json:"updatedTs"` DisplayTs int `json:"displayTs"` Content string `json:"content"` Visibility string `json:"visibility"` Pinned bool `json:"pinned"` CreatorName string `json:"creatorName"` CreatorUsername string `json:"creatorUsername"` ResourceList []interface{} `json:"resourceList"` RelationList []interface{} `json:"relationList"` } func GetMemosJson(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { http.Error(w, "参数解析错误", http.StatusInternalServerError) } id := r.Form.Get("id") resp, err := http.Get(config.Cfg.MemosURL + "/api/v1/memo/" + id) if err != nil { http.Error(w, "无法获取文章数据", http.StatusInternalServerError) return } defer resp.Body.Close() var info MemoInfo err = json.NewDecoder(resp.Body).Decode(&info) // 使用json.NewDecoder解码JSON数据 if err != nil { http.Error(w, "无法解析文章数据", http.StatusInternalServerError) return } compileRegex := regexp.MustCompile("(?s)```json\n(.*?)```") matchArr := compileRegex.FindStringSubmatch(info.Content) if len(matchArr) > 0 { source := make([]byte, 4096) source = []byte(fmt.Sprintf("[%v]", matchArr[len(matchArr)-1])) w.Header().Add("Content-Type", "application/octet-stream;charset=utf-8") w.Header().Add("Content-Disposition", "attachment;filename="+info.Name+".json") _, err = w.Write(source) if err != nil { http.Error(w, "无法解析源数据", http.StatusInternalServerError) return } return } http.Error(w, "无法解析页面请求"+id, http.StatusInternalServerError) return }