原文: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. flex布局(主要分清楚容器和条目)

    设置在容器上面的属性:flex-direction.flex-wrap.flex-flow.justify-content.align-items.align-content1.flex-direct ...

  2. (转)淘淘商城系列——SSM框架整合之Service层整合

    http://blog.csdn.net/yerenyuan_pku/article/details/72721108 上文我们一起学习了Dao层的整合,本文将教大家如何整合Service层. 我们需 ...

  3. chgrp - 改变文件的组所有权

    总览 chgrp [选项] 组文件... POSIX 选项: [-R] [--] Austin 草拟选项: [-hHLPR] GNU 团体指示: [--reference=rfile] GNU 选项 ...

  4. react link引入外部css样式的坑

    刚开始的代码是这样的,使用react router4.x写的demo路由跳转后,页面的没有渲染,是因为没有引入外部css文件(或者说引入外部文件路径错误) <!DOCTYPE html> ...

  5. winpcap编程设置过滤器之指定获取某个网站的数据

    下面,我将以 乱世隋唐页游 为例,通过编码获取这里面的数据. 游戏图: 我是乱世隋唐的网址是:www.917st.com 这个是官网网址的服务器地址.  42.62.0.14 我玩的游戏服是84区.网 ...

  6. bzoj3994: [SDOI2015]约数个数和(反演+结论?!)

    这题做的历程堪称惊心动魄 刚刚学了莫比乌斯反演的我高高兴兴的和cbx一起反演式子 期间有突破,有停滞,有否定 然后苟蒻的我背着cbx偷偷打开了题解 看到了 我...... 去你的有个性质啊(当然还是自 ...

  7. android网络图片自动轮播 githhub地址

    https://github.com/panxw/android-image-indicator

  8. IOS 3D UI --- CALayer的transform扩展

    http://www.cocoachina.com/bbs/read.php?tid=117061 例子代码可以在 http://download.csdn.net/detail/worldmatri ...

  9. react-native Android WARNING: API 'variant.getMergeAssets()' is obsolete and has been replaced with 'variant.getMergeAssetsProvider()'.

    android Studio 中打开react-native项目的android文件夹 在sync的过程中 发生warning: WARNING: API 'variant.getMergeAsset ...

  10. 用element-ui的走马灯carousel轻松实现自适应全屏banner图

    写在前面:网站轮播图建议使用swiper组件,非常方便快捷.vue轮播图插件之vue-awesome-swiper 接手一个项目,轮播图是用element-ui的carousel实现的,看起来效果还不 ...