golang dns服务器_2020年在golang中建立网络服务器的初学者指南

news/2024/7/24 9:37:25 标签: 网络, linux, python, http, golang

golang dns服务器

In this article, I’ll teach you how to create simple web servers with the Go language.

在本文中,我将教您如何使用Go语言创建简单的Web服务器。

Golang入门 (Getting Started With Golang)

It would be best if you have Go installed on your device, and this can be a Windows, Mac, or Linux device. Before you start to write Go code, you need to create a new directory to store your files in:

最好在设备上安装Go,并且它可以是Windows,Mac或Linux设备。 在开始编写Go代码之前,您需要创建一个新目录来将文件存储在以下位置:

$ mkdir newserver
$ cd newserver

In this folder, you create your main application file, main.go:

在此文件夹中,创建您的主应用程序文件main.go

package mainimport (
"fmt"
)

We import the fmt package from the standard Go library. We will need this in the future.

我们从标准Go库中导入fmt包。 将来我们会需要这个。

你好世界的例子 (Hello World Example)

We are going to start with a basic example of a web server. You need to add the following import to your code:

我们将从网络服务器的基本示例开始。 您需要在代码中添加以下导入:

import (
"fmt"
"net/http"
)

注册请求处理程序 (Registering a Request Handler)

First, create a handler that receives all incoming HTTP connections from browsers, HTTP clients, or API requests. A handler in Go is a function with this signature:

首先,创建一个处理程序,以接收来自浏览器,HTTP客户端或API请求的所有传入HTTP连接。 Go中的处理程序是具有以下签名的函数:

func (w http.ResponseWriter, r *http.Request)

This function takes two arguments: an http.ResponseWriter, which is where you write your text/HTML response and an http.Request, which contains all information about this HTTP request, including things like the URL and header fields.

此函数有两个参数: http.ResponseWriter (在其中编写文本/ HTML响应)和http.Request (在此包含有关此HTTP请求的所有信息,包括URL和标头字段)。

To register the request handler, we use:

要注册请求处理程序,我们使用:

http.HandleFunc("/", func (w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello Medium, you've requested: %s\n", r.URL.Path)
})

港口 (Ports)

We need to add a port to make a web server listen to a specific address and port:

我们需要添加端口以使Web服务器侦听特定的地址和端口:

http.ListenAndServe(":80", nil)

完整代码示例 (Full code example)

Your full code should look like this:

您的完整代码应如下所示:

静态资产 (Static Assets)

To serve static assets like JavaScript, CSS, and images, we use the inbuilt http.FileServer:

为了提供JavaScript,CSS和图像等静态资产,我们使用内置的http.FileServer

fs := http.FileServer(http.Dir("static/"))

Once our file server is in place, we just need to point a URL path at it.

文件服务器安装到位后,我们只需要指向它的URL路径即可。

http.Handle("/static/", http.StripPrefix("/static/", fs))

路由 (Routing)

One thing Go doesn’t do very well is complex request routing, like segmenting a request URL into single parameters. Fortunately, there is a very popular package for this, which is well known in the Go community for its good code quality. This package is called gorilla/mux.

Go做得不好的一件事是复杂的请求路由,例如将请求URL分割为单个参数。 幸运的是,有一个非常受欢迎的程序包,该程序包在Go社区中以其良好的代码质量而闻名。 该程序包称为大猩猩/多路复用器。

安装套件 (Install the package)

To install this package in Go is very simple:

在Go中安装此软件包非常简单:

go get -u github.com/gorilla/mux

创建一个新的路由器 (Create a new router)

First, create a new request router. The router is the main router for your web application and will later be passed as a parameter to the server.

首先,创建一个新的请求路由器。 路由器是Web应用程序的主要路由器,以后将作为参数传递给服务器。

r := mux.NewRouter()

网址参数 (URL parameters)

With this package, it’s very easy to use URL parameters. It looks like this:

使用此软件包,可以很容易地使用URL参数。 看起来像这样:

r.HandleFunc("/user/{username}", func(w http.ResponseWriter, r *http.Request) {
//Route code})

定义请求类型 (Define the type of request)

You can easily define your type of request (for example, a GET or POST request) by adding the following line of code:

通过添加以下代码行,您可以轻松定义请求类型(例如GET或POST请求):

r.HandleFunc("/user/{username}", func(w http.ResponseWriter, r *http.Request) {
//Route code}).Methods("GET")

注册路由器 (Register the router)

When you have set up your router, you need to register it to make it work:

设置路由器后,您需要对其进行注册以使其工作:

http.ListenAndServe(":80", r)

完整代码示例 (Full code example)

HTML模板 (HTML Templates)

When building a web server (unless you are building a REST API) you want to use HTML pages to display your data.

在构建Web服务器时(除非正在构建REST API),您要使用HTML页面显示数据。

Therefore you need to import a new package:

因此,您需要导入一个新包:

import (     "html/template"     "net/http" )

When you have built your own HTML page, you can put it in your templates folder. Then add the following code to your main func:

构建自己HTML页面后,可以将其放在templates文件夹中。 然后将以下代码添加到您的主要func

This will load your HTML template into your web server’s route.

这会将HTML模板加载到Web服务器的路由中。

结论 (Conclusion)

I hope you learned a lot from this beginner's guide to web servers in Go. You learned the fundamentals of web programming for Go, so you should be able now to figure new things out and go on your own web development journey!

希望您从Go的Web服务器入门指南中学到很多东西。 您已经了解了Go语言Web编程的基础知识,因此您现在应该能够找到新的东西并继续自己的Web开发旅程!

翻译自: https://medium.com/better-programming/the-beginners-guide-to-setting-up-a-webserver-in-golang-in-2020-5db1478b117d

golang dns服务器


http://www.niftyadmin.cn/n/1468970.html

相关文章

oracle异构mysql_配置Oracle GoldenGate异构oracle到mysql同步

最近研究了一下oracle Goldengate异构同步的过程,真是几天不用手生,敲命令竟然如此生疏。不过还算顺利,经过一番折腾终于好了。环境描述:192.0.2.101( Oracle ) —>192.0.2.102 (Mysql )版本:操作系统:redhat6.5Ora…

程序运行出现内部应用程序错_应用程序和网站在什么上运行

程序运行出现内部应用程序错This is the first article in my series looking into the inner workings of ‘the Cloud” and the data centres that host them. With the proliferation of apps and websites, and with seemingly everything being connected to ‘the cloud…

java mysql 分布式锁_死磕 java同步系列之mysql分布式锁

欢迎关注我的公众号“彤哥读源码”,查看更多源码系列文章, 与彤哥一起畅游源码的海洋。(手机横屏看源码更方便)问题(1)什么是分布式锁?(2)为什么需要分布式锁?(3)mysql如何实现分布式锁?(4)mysql分布式锁的优点和缺点?…

centos下mysql主从分离_centos下的mysql 主从分离

1、分别同时打开主机和从机的my.cnf命令进行设置vim /etc/my.cnf在[mysqld]下 ?自己填数字,但是不能重复log-binserver-id?2、在主机进行操作,进入mysql主机赋予从机权限:grant replication slave, replication client on *.*…

mysql修改binlog格式_my15_ mysql binlog格式从mixed修改为row格式

由于主库繁忙,就在从库上修改binlog格式1. 从库切日志mysql> flush logs;Query OK, 0 rows affected (0.00 sec)mysql> flush logs;Query OK, 0 rows affected (0.00 sec)mysql> flush logs;Query OK, 0 rows affected (0.00 sec)2. 验证修改格式之前的日志…

软件设计 抽象_调试抽象给软件工程师带来正念的好处

软件设计 抽象It’s been a wild week. You and your team have been engaged in an all-out war with the codebase for the past two sprints. There’s this new integration with a partner that’s close to being shipped, and it promises bountiful revenue and volumi…

mysql 用户表记录表_MySql之行记录的详细操作,创建用户以及库表的授权

一 介绍MySQL数据操作: DML在MySQL管理软件中,可以通过SQL语句中的DML语言来实现数据的操作,包括使用INSERT实现数据的插入UPDATE实现数据的更新使用DELETE实现数据的删除使用SELECT查询数据以及。本节内容包括:插入数据更新数据删…

大数据开发转职可以做什么_你可以成为全职开发人员吗

大数据开发转职可以做什么I was thinking of a full-stack mindset last week, and I decided to write a short essay about the “fullstack developer” concept, especially in web development.我上周想到的是全栈思维,所以我决定写一篇有关“全栈开发人员”概…