原文:https://tutorialedge.net/post/golang/creating-simple-web-server-with-golang/

----------------------------------------------------------------------------------------------------------------------------------------------------------------------

In this tutorial we’ll be focusing on creating a very simple web server using the net/http package. If you’ve ever used something like Node’s ExpressJS or Python’s Tornado, then you should hopefully see some similarities to how things are handled.

Creating a Basic Web Server

Ok, so to begin with we’ll create a very simple web server that will just return whatever the URL path is of your query. This will be a good base from which we can build on top of.

package main

import (
"fmt"
"html"
"log"
"net/http"
) func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
}) http.HandleFunc("/hi", func(w http.ResponseWriter, r *http.Request){
fmt.Fprintf(w, "Hi")
}) log.Fatal(http.ListenAndServe(":8081", nil)) }

In the above code we essentially define two different Handlers. These handlers are what respond to any http request that match the string pattern we define as the first parameter. So essentially whenever a request is made for the home page or http://localhost:8081/, we’ll see our first handler respond as the query matches that pattern.

Running Our Server

Ok so now that we’ve created our own very simplistic server we can try running it by typing go run server.go into our console. This usually asks me for permission so accept that and then head over to your browser and head to http://localhost:8081/world. On this page you should hopefully see your query string echoed back to you in true “hello world” fashion.

Adding a bit of Complexity

So now that we’ve got a basic web server set up, let’s try incrementing a counter every time a specific url is hit. Due to the fact that the web server is asynchronous, we’ll have to guard our counter using a mutex in order to prevent us from being hit with race-condition bugs.

package main

import (
"fmt"
"log"
"net/http"
"strconv"
"sync"
) var counter int
var mutex = &sync.Mutex{} func echoString(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "hello")
} func incrementCounter(w http.ResponseWriter, r *http.Request) {
mutex.Lock()
counter++
fmt.Fprintf(w, strconv.Itoa(counter))
mutex.Unlock()
} func main() {
http.HandleFunc("/", echoString) http.HandleFunc("/increment", incrementCounter) http.HandleFunc("/hi", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hi")
}) log.Fatal(http.ListenAndServe(":8081", nil)) }

Run this and then navigate to http://localhost:8081/increment and you should see the current count which will be locked, incremented and then unlocked every time you make a request to that page.

Serving Static Files

Ok, so now that we’ve set up a simple server in go, it’s time to start serving some static files. Create a static folder within your project’s directory and then create some simple html files. For this example I’m just serving back the following:

<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>Hello World!</h2>
</body>
</html>

Once you’ve got this then we can then modify our web server code to use the http.ServeFile method. Essentially this will take in the url of the request made to the server, and if it contains say index.html then it would return the index.html file, rendered as html in the browser. If we were to create an edit.html page and send a request to http://localhost:8081/edit.html then it would return whatever html content you choose to put in that edit.html page.

package main

import (
"fmt"
"log"
"net/http"
) func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, r.URL.Path[1:])
}) http.HandleFunc("/hi", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hi")
}) log.Fatal(http.ListenAndServe(":8081", nil)) }

Checking it Works

Again run the server and navigate to http://localhost:8081/index.html and you should hopefully see your very simple index.html file rendered in all it’s glory.

I hope you found this tutorial useful and if you did then please let me know in the comments section below! This is part one of a series of GoLang tutorials in which we play around with APIs and creating servers so stay tuned for more!

Creating A Simple Web Server With Golang的更多相关文章

  1. Server Develop (九) Simple Web Server

    Simple Web Server web服务器hello world!-----简单的socket通信实现. HTTP HTTP是Web浏览器与Web服务器之间通信的标准协议,HTTP指明了客户端如 ...

  2. Creating a Simple Web Service and Client with JAX-WS

    Creating a Simple Web Service and Client with JAX-WS 发布服务 package cn.zno.service.impl; import javax. ...

  3. Chapter 1: A Simple Web Server

    这算是一篇读书笔记,留着以后复习看看. Web Server又称为Http Server,因为它使用HTTP协议和客户端(一般是各种各样的浏览器)进行通信. 什么是HTTP协议呢? HTTP协议是基于 ...

  4. A Simple Web Server

    介绍 在过去20几年里,网络已经在各个方面改变了我们的生活,但是它的核心却几乎没有什么改变.多数的系统依然遵循着Tim Berners-Lee在上个世纪发布的规则.大多数的web服务器都在用同样的方式 ...

  5. Simple Web API Server in Golang (1)

    To be an better Gopher, get your hands dirty. Topcoder offered a serials of challenges for learning ...

  6. Simple Web API Server in Golang (2)

    In this challenge, I tried to implement a simple OAuth2 server basing on Simple Web API Server in [1 ...

  7. Creating a simple static file server with Rewrite--reference

    Today, I’d like to take a quick moment to demonstrate how to make a simple file server using Rewrite ...

  8. a simple and universal interface between web servers and web applications or frameworks: the Python Web Server Gateway Interface (WSGI).

    WSGI is the Web Server Gateway Interface. It is a specification that describes how a web server comm ...

  9. [Docker] Build a Simple Node.js Web Server with Docker

    Learn how to build a simple Node.js web server with Docker. In this lesson, we'll create a Dockerfil ...

随机推荐

  1. 最新WIN10系统32位和64位纯净版自动激活版1010074 V2015年

    系统来自:系统妈 本系统定位于个人在家庭.网吧.办公环境使用,采用久经考验的精简方法和体积压缩技术,在小巧体积中提供了几乎100%的原版Win10兼容性.经过在多个版本的更新和升级过程后,已经被证明能 ...

  2. 阿里云ECS安装sqlserver,本地无法连接问题排查思路

    1. 阿里云控制台-对应的ECS实例的安全组是否添加了响应的端口(1433)可以访问: 2. 服务器-sqlserver服务是否开启: 3. 服务器-sqlserver配置器,对应的端口是否启用,已经 ...

  3. 哈尔滨工程大学ACM预热赛 补题

    链接:https://ac.nowcoder.com/acm/contest/554/A来源:牛客网 小虎刚刚上了幼儿园,老师让他做一个家庭作业:首先画3个格子,第二行有2个格子,第三行有1个格子. ...

  4. vue工程化与路由router

    一.介绍     vue.js 是 目前 最火的前端框架,vue.js 兼具 angular.js 和 react.js 的优点,并剔除它们的缺点.并且提供了很多的周边配套工具 如vue-router ...

  5. win下配置qt creator 能够执行c/c++

    首先需要相关包共四个: qt-win-opensource-4.8.5-mingw.exe qt-creator-windows-opensource-2.8.1.exe MinGW-gcc440_1 ...

  6. 复制Windows的等宽字体到Linux

    1.从Windows的Fonts目录下复制字体 2.在Linux的/usr/share/fonts目录下创建子目录例如:sudo mkdir /usr/share/fonts/win 3.复制字体到该 ...

  7. Hadoop环境搭建、启动和管理界面查看

    一.hadoop环境搭建: 1. hadoop 6个核心配置文件的作用:core-site.xml:核心配置文件,主要定义了我们文件访问的格式 hdfs://hadoop-env.sh:主要配置我们的 ...

  8. Oracle 学习之:ASCII,CHR函数的作用和用法

    对于ASCII以及CHR函数的用法,Oracle给出的解释是: ASCII(x)gets the ASCII value of the character X, CHR() and ASCII() h ...

  9. rem怎么算

    * rem : html根标签的 font-size决定* em 相对于父标签的font-size 决定的* 设计稿的宽一般都是 750px ---> 20px* 750px 1rem = 10 ...

  10. [kuangbin带你飞]专题四 最短路练习

    对于最短路,我主要使用的就是dijkstra,Floyd,SPFA这三个算法.先来介绍一下这三个算法. 1. dijkstra算法.它适用于边权为正的情况,它是单源最短路,就是从单个源点出发到所有的结 ...