繁体   English   中英

在 Linux 服务器上提供 Go API

[英]Serve Go API on Linux server

在学习了几个教程之后,我仍然无法让我的 API 正常工作。 它在本地工作正常,但是当我将它添加到服务器上时,我似乎无法连接。 有人可以带我过去吗?

我正在使用带有 NGINX 的 Ubuntu 18.04 服务器。 API 是用 GoLang 编写的。

我的文件夹结构是:

/var/www/example.com/

/var/www/example.com/GoAPI/

显然 API 位于 GoAPI 文件夹中(我知道,命名不好,但仅用于学习目的)。

API 使用 Gorilla Mux 并在“:8000”上提供服务。 我的前端是用 Typescript 编写的,并使用 Axios。 它尝试连接到“ http://example.com/GoAPI/ ”。

我有我的标准服务器块(只有 1 个 atm),它刚刚定义了我的服务器名和“尝试文件”,目前就是这样。 我尝试添加代理通行证,但这似乎没有任何作用。

我现在得到的错误是“错误:“网络错误”和 CORS 错误,即使 CORS 确实在本地工作并且我添加了 Gorilla Mux 为您提供的 CORS 方法。

希望有人可以帮助我。

目前服务器块文件:

server {
  listen 80;
  listen [::]:80;

  root /var/www/example.com;
  index index.html index.htm index.nginx-debian.html;

  server_name example.com www.example.com;

  location / {
        try_files $uri $uri/ =404;
  }
}

Nginx 配置只是开箱即用,我没有更改任何内容。

我的配置文件如下所示:

user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf;

events {    worker_connections 768;     # multi_accept on; }

http {

    ##  # Basic Settings    ##

    sendfile on;    tcp_nopush on;  tcp_nodelay on;     keepalive_timeout 65;   types_hash_max_size 2048;   # server_tokens off;

    server_names_hash_bucket_size 64;   # server_name_in_redirect off;

    include /etc/nginx/mime.types;  default_type application/octet-stream;

    ##  # SSL Settings  ##

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE  ssl_prefer_server_ciphers on;

    ##  # Logging Settings  ##

    access_log /var/log/nginx/access.log;   error_log /var/log/nginx/error.log;

    ##  # Gzip Settings     ##

    gzip on;

    # gzip_vary on;     # gzip_proxied any;     # gzip_comp_level 6;    # gzip_buffers 16 8k;   # gzip_http_version 1.1;    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##  # Virtual Host Configs  ##

    include /etc/nginx/conf.d/*.conf;   include /etc/nginx/sites-enabled/*; }


#mail {
#   # See sample authentication script at:
#   # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
#   # auth_http localhost/auth.php;
#   # pop3_capabilities "TOP" "USER";
#   # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
#   server {
#       listen     localhost:110;
#       protocol   pop3;
#       proxy      on;
#   }
#
#   server {
#       listen     localhost:143;
#       protocol   imap;
#       proxy      on;
#   }
#}

您目前没有在 Nginx 配置文件中设置任何内容来连接到端口 8000 上的服务。最简单快捷的方法是使用 ProxyPass 指令并将位置上下文添加到服务器块内的配置文件中。

例如,你的应该看起来像这样

server {
    listen 80;
    server_name example.com;

    location /GoAPI {
        proxy_pass http://127.0.0.1:8000;
    }
 }

请记住,无论何时调整 Nginx 配置文件,都必须重新加载/重新启动服务以使更改生效。 您还可以使用nginx -t测试文件以确保语法正确。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM