Creating A Simple Web Server With Golang
原文: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的更多相关文章
- Server Develop (九) Simple Web Server
		
Simple Web Server web服务器hello world!-----简单的socket通信实现. HTTP HTTP是Web浏览器与Web服务器之间通信的标准协议,HTTP指明了客户端如 ...
 - 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. ...
 - Chapter 1: A Simple Web Server
		
这算是一篇读书笔记,留着以后复习看看. Web Server又称为Http Server,因为它使用HTTP协议和客户端(一般是各种各样的浏览器)进行通信. 什么是HTTP协议呢? HTTP协议是基于 ...
 - A Simple Web Server
		
介绍 在过去20几年里,网络已经在各个方面改变了我们的生活,但是它的核心却几乎没有什么改变.多数的系统依然遵循着Tim Berners-Lee在上个世纪发布的规则.大多数的web服务器都在用同样的方式 ...
 - Simple Web API Server in Golang (1)
		
To be an better Gopher, get your hands dirty. Topcoder offered a serials of challenges for learning ...
 - 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 ...
 - 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 ...
 - 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 ...
 - [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 ...
 
随机推荐
- rem手机端页面自适应完美解决方案(最新)
			
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
 - [转载]iTOP-4418开发板Ubuntu系统烧写方法分享
			
本文转自迅为论坛:http://topeetboard.com 开发平台:iTOP-4418开发板系统:Ubuntu 1. TF卡读写速度测试烧写 Ubuntu 对于 TF 卡的要求比较高,很多老旧的 ...
 - 【java】查重类的实现
			
import java.util.Vector; public class ElementCheck { // 重复优先 static Vector<Integer> CheckSameE ...
 - Axure 9 面板折叠显示隐藏
			
1 首先放置一个面板1作为点击事件: 2 另外一个面板2或者其他组建,将其设置为动态面板,然后隐藏 3 给面板1添加如下事件,即可: 4 我们点击面板1,可以实现展开隐藏面板2的动态效果
 - CAD交互绘制带周长面积的矩形框(com接口)
			
主要用到函数说明: _DMxDrawX::DrawLine 绘制一个直线.详细说明如下: 参数 说明 DOUBLE dX1 直线的开始点x坐标 DOUBLE dY1 直线的开始点y坐标 DOUBLE ...
 - webstorm 设置ES6语法支持以及添加vuejs开发配置
			
参考文章:https://blog.csdn.net/diligentkong/article/details/75040651
 - 关于nested exception is org.apache.ibatis.binding.BindingException:Parameter '***' not found报错解决
			
几天晚上遇到的奇怪的问题 传入的参数名一直没有变 但是从mapper到xml似乎有一个找不到参数的报错,实际上只要在Mapper接口形参前加“@Param(“形参名称”)”就可以了
 - 在 VS2015+EF6.0中使用Mysql 遇到的坑
			
1)首先是要在vs2015中安装mysql Database 默认是不存在的 1)下载mysql-connector-net-6.9.9.msi 地址:https://dev.mysql.com ...
 - Spring对象类型——单例和多例
			
由于看淘淘商城的项目,涉及到了项目中处理spring中bean对象的两种类型,分别是单例和多例,就在此记录一下,方便加深理解,写出更加健壮的代码. 一.单例和多例的概述 在Spring中,bean可以 ...
 - switch、try-catch
			
记录 1. 使用对象代替 switch 和 if-else 2. 根据返回数据是否能转成对象,取值 如果返回是数字字符串,直接返回,如果返回是对象,取对应的key值,再返回 其它情况,返回空 {{ o ...