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 ...
随机推荐
- 框架开发之Java注解的妙用
注解的好处:1.能够读懂别人写的代码,特别是框架相关的代码.2.本来可能需要很多配置文件,需要很多逻辑才能实现的内容,就可以使用一个或者多个注解来替代,这样就使得编程更加简洁,代码更加清晰.3.(重点 ...
- hibernate 离线查询(DetachedCriteria)
离线查询使用DetachedCriteria对象设置限制条件,然后再通过session获取Criteria对象. 使用场景: 例如Biz类和Dao类,在Dao类中利用session操作CRUD,如果你 ...
- Java 字符串格式化 String.format() 的使用
常规类型的格式化 String类的format()方法用于创建格式化的字符串以及连接多个字符串对象.熟悉C语言的同学应该记得c语言的sprintf()方法,两者有类似之处.format()方法有两种重 ...
- CPU怎么计算1+1----CPU计算的电路基础
从<十进制和二进制的运算---我所理解到的人类的运算的本质>这里我们知道,人类进行运算的本质是查表,并且我们存储的表是有限的.那么计算机是怎进行四则运算的呢,也是查表吗,肯定不是,今天,我 ...
- Hibernate修改操作 删除操作 查询操作 增加操作 增删改查 Hibernate增删查改语句
我用的数据库是MySQL,实体类叫User public class User { private Integer uid; private String username; private Stri ...
- 面试之Spring
一.IoC IoC(Inversion of Control):控制反转(是把传统上由程序代码直接操控的对象的生成交给了容器来实现, 通过容器来实现对象组件的装配和管理.所谓"控制反转&qu ...
- Spring Boot . 3 -- Spring Boot Auto_configuration 是如何实现的?
配置是Spring 框架的重要核心之一,所以Spring 应用能够正常的跑起来肯定是需要配置的,但是使用的Spring Boot 后很多配置没有做,那么AUTO-CONFIGURATION 到底是怎么 ...
- react之webpack
1. 下载相关模块包 * 创建package.json ``` npm init ``` * react相关库 package-lock.json ``` npm install react reac ...
- h5移动端常见虚拟键盘顶起底部导航栏解决办法
在h5移动端开发中相信很多朋友跟我一样都会遇到页面底部导航被虚拟键盘顶起的问题,自己在网上找到的解决办法拿出来与大家分享,有不完美之处还望见谅,有更好的解决办法可以贴出来大家一起互相学习!! var ...
- drupal8 用户指南
一句话概括 - 官方文档 概念- Drupal是个内容管理系统哦 那么,什么是内容管理系统? 就是用户自己编辑自己的网站内容的一个系统. 那么,什么是Drupal呢? Drupal是一个通过模块和主题 ...