> /tmp/urls.txt 我在 c 中的 get 比使用我的 go 代码花费的时间要长" />
登录
首页 >  Golang >  Go问答

https 获取使用 libcurl 与 golang

来源:stackoverflow

时间:2024-02-27 14:18:26 120浏览 收藏

哈喽!今天心血来潮给大家带来了《https 获取使用 libcurl 与 golang》,想必大家应该对Golang都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到,若是你正在学习Golang,千万别错过这篇文章~希望能帮助到你!

问题内容

比如说,我有一个网址列表:

$ for i in `seq 1 90`; do echo "$random$random.blogspot.com" ; done >> /tmp/urls.txt

我在 c 中的 get 比使用我的 go 代码花费的时间要长得多。

这是 c 代码:

n_memory.c

#include 
#include 
#include 
#include 

struct memorystruct {
  char *memory;
  size_t size;
};

static size_t
writememorycallback(void *contents, size_t size, size_t nmemb, void *userp)
{
  size_t realsize = size * nmemb;
  struct memorystruct *mem = (struct memorystruct *)userp;
  char *ptr = realloc(mem->memory, mem->size + realsize + 1);
  if(ptr == null) {
    printf("not enough memory (realloc returned null)\n");
    return 0;
  }

  mem->memory = ptr;
  memcpy(&(mem->memory[mem->size]), contents, realsize);
  mem->size += realsize;
  mem->memory[mem->size] = 0;
  return realsize;
}

int try_url(char *url);

int main(int argc, char **argv){

        if (argc < 2){
                fprintf(stderr, "error, argc\n");
                return 1;
        }
        file *fp = fopen(argv[1],"r");
        if (!fp){
                fprintf(stderr, "fopen, argc\n");
                return 1;
        }
        int count = 1;
        char _line[2048];
        char url[8192];
        while ( fgets(_line, 1024, fp) ){
               _line[strcspn(_line, "\r\n")] = 0;
                char *part1 = "https://dns.google.com/resolve?name=";
                char *part3 = "&type=a";
                snprintf(url, 4096, "%s%s%s", part1, _line, part3);
                printf("%d %s\n", count, url);
                try_url(url);
                if (count > 80){
                        break;
                }
                count++;
        }

        //try_url(argv[1]);
        puts("done");
        return 0;
}



int try_url(char *url)
{
  curl *hnd;
  curlcode res;
  struct curl_slist *slist1;
  struct memorystruct chunk;

  chunk.memory = malloc(1);  /* will be grown as needed by the realloc above */
  chunk.size = 0;    /* no data at this point */

  curl_global_init(curl_global_all);
  hnd = curl_easy_init();
  curl_easy_setopt(hnd, curlopt_noprogress, 1l);
  curl_easy_setopt(hnd, curlopt_maxredirs, 50l);
  curl_easy_setopt(hnd, curlopt_http_version, (long)curl_http_version_2tls);
  curl_easy_setopt(hnd, curlopt_ssl_verifypeer, 0l);
  curl_easy_setopt(hnd, curlopt_ssl_verifyhost, 0l);
  curl_easy_setopt(hnd, curlopt_tcp_keepalive, 1l);
  curl_easy_setopt(hnd, curlopt_resolve, slist1);

  slist1 = null;
  slist1 = curl_slist_append(slist1, "dns.google.com:443:172.217.5.110");

  curl_easy_setopt(hnd, curlopt_ssl_verifypeer, 0);
  curl_easy_setopt(hnd, curlopt_ssl_verifyhost, 0);
  curl_easy_setopt(hnd, curlopt_url, url);
  curl_easy_setopt(hnd, curlopt_writefunction, writememorycallback);
  curl_easy_setopt(hnd, curlopt_writedata, (void *)&chunk);
  curl_easy_setopt(hnd, curlopt_useragent, "libcurl-agent/1.0");
  res = curl_easy_perform(hnd);
  if(res != curle_ok) {
    fprintf(stderr, "curl_easy_perform() failed: %s\n",
            curl_easy_strerror(res));
  }
  else {
    printf("%lu bytes retrieved\n", (unsigned long)chunk.size);
  }

  curl_easy_cleanup(hnd);
  free(chunk.memory);
  curl_global_cleanup();
  return 0;
}

这是执行代码:

n_get.go

package main

import (
        "bufio"
        "fmt"
        "log"
        "net/http"
        "os"
        "time"
)

func main() {

        if len(os.args) < 2 {
                fmt.println("invalid usage")
                os.exit(1)
        }

        filename := os.args[1]

        f, err := os.open(filename)
        checkerr(err)
        defer f.close()
        fscanner := bufio.newscanner(f)
        i := 1
        for fscanner.scan() {
                text := fscanner.text()
                // https://dns.google.com/resolve?name=1.bp.blogspot.com&type=a
                url := "https://dns.google.com/resolve?name=" + text + "&type=a"
                //fmt.println(i, url);
                get_url(url)
                if i == 80 {
                        break
                }
                i = i + 1
        }

        fmt.println("hello!")
}

func checkerr(err error) {
        if err != nil {
                fmt.println(err)
                log.fatal(err)
        }
}

func get_url(url string) int {
        fmt.println(url)
        t1 := time.now()
        resp, err := http.get(url)
        t2 := time.now()
        checkerr(err)
        fmt.println(resp.status)
        diff := t2.sub(t1)
        fmt.println(url, "took us", diff)
        if resp.statuscode == 200 {
                fmt.println("ok")
                return 0
        } else {
                fmt.println("failed")
                return 1
        }

}

我什至尝试使用 --resolve 选项来协助 libcurl 传递它可以使用的 ip 地址,从而使其不必进行名称查找。然而这似乎并没有多大帮助。

即使尝试使用curl 的--insecure 选项,仍然没有多大作用。

以下是执行 80 个 https get 所需的时间:

+------------------+-----------------+
|      golang      |   c             |
+------------------------------------+
| real    0m2.670s |real    0m20.024s|
| user    0m0.555s |user    0m13.393s|
| sys     0m0.086s |sys     0m0.242s |
+------------------------------------+

这有点不平衡,我正在寻找缩小差距的指针。 如何提高 c 代码的速度?任何积分将不胜感激。


解决方案


首先,不要每次尝试都运行所有的curl init。这样做一次。

我认为您也不需要每次都执行所有选项。

也不要执行 1 字节的 malloc。只需将其保留为 NULL 即可。 Realloc 知道如何处理它。

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>