|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "encoding/json" |
| 6 | + "io/ioutil" |
| 7 | + "log" |
| 8 | + "net/http" |
| 9 | +) |
| 10 | + |
| 11 | +type JsL4CodeSnippets []struct { |
| 12 | + Lang string |
| 13 | + Code string |
| 14 | +} |
| 15 | + |
| 16 | +type JsL3Detail struct { |
| 17 | + Content string |
| 18 | + CodeSnippets JsL4CodeSnippets |
| 19 | +} |
| 20 | + |
| 21 | +type JsL2Question struct { |
| 22 | + Question JsL3Detail |
| 23 | +} |
| 24 | + |
| 25 | +type JsL1Data struct { |
| 26 | + Data JsL2Question |
| 27 | +} |
| 28 | + |
| 29 | +func getGraphql(p problem) (string, string) { |
| 30 | + // req := newReq() |
| 31 | + |
| 32 | + params := make(map[string]interface{}) |
| 33 | + params["operationName"] = "questionData" |
| 34 | + params["query"] = "query questionData($titleSlug: String!) { question(titleSlug: $titleSlug) { content codeSnippets { lang code } } }" |
| 35 | + titleSlug := make(map[string]string) |
| 36 | + titleSlug["titleSlug"] = p.TitleSlug |
| 37 | + params["variables"] = titleSlug |
| 38 | + |
| 39 | + // Make this JSON |
| 40 | + postJson, _ := json.Marshal(params) |
| 41 | + |
| 42 | + // http.POST expects an io.Reader, which a byte buffer does |
| 43 | + postContent := bytes.NewBuffer(postJson) |
| 44 | + |
| 45 | + resp, err := http.Post("https://leetcode.com/graphql", "application/json", postContent) |
| 46 | + if err != nil { |
| 47 | + log.Fatal("getGraphql: POST Error: " + err.Error()) |
| 48 | + } |
| 49 | + |
| 50 | + defer resp.Body.Close() |
| 51 | + |
| 52 | + if resp.StatusCode != 200 { |
| 53 | + log.Fatal("抓题失败 code: " + resp.Status) |
| 54 | + } |
| 55 | + |
| 56 | + respBytes, err := ioutil.ReadAll(resp.Body) |
| 57 | + if err != nil { |
| 58 | + log.Fatal("getGraphql: Read Error: " + err.Error()) |
| 59 | + } |
| 60 | + |
| 61 | + //byte数组直接转成string,优化内存 |
| 62 | + // str := (*string)(unsafe.Pointer(&respBytes)) |
| 63 | + // fmt.Printf("%#v\n", *str) |
| 64 | + |
| 65 | + res := &JsL1Data{} |
| 66 | + json.Unmarshal(respBytes, &res) |
| 67 | + |
| 68 | + code := "" |
| 69 | + for _, qc := range res.Data.Question.CodeSnippets { |
| 70 | + if qc.Lang == "Go" { |
| 71 | + code = qc.Code |
| 72 | + } |
| 73 | + } |
| 74 | + return res.Data.Question.Content, code |
| 75 | +} |
0 commit comments