HTTP Server Basics

Use net/http package and useful third-party packages by building simple servers.

Building a Simple Server

package main

import (
"fmt"
"net/http"
) func hello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello %s\n", r.URL.Query().Get("name"))
} func main() {
http.HandleFunc("/hello", hello)
http.ListenAndServe(":8000",nil)
}

Run the above program and test it.

curl -i http://localhost:8000/hello?name=eric

You can also use http.ListenAndServeTLS(), which will start a server using HTTPS and TLS.

Build a Simple Router

package main

import (
"fmt"
"net/http"
) type router struct {
} func (r *router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
switch req.URL.Path {
case "/a":
fmt.Fprintf(w, "Executing /a\n")
case "/b":
fmt.Fprintf(w, "Executing /b\n")
case "/c":
fmt.Fprintf(w, "Executing /c\n")
default:
http.Error(w, "404 Not Found", 404)
}
} func main() {
var r router
http.ListenAndServe(":8000", &r)
}

Test the above program by the following commands.

curl http://localhost:8000/a
curl http://localhost:8000/d

Building simple Middleware

A simple middleware, which is a sort of wrapper that will execute on all incoming requests regardless of the destination function.

package main

import (
"fmt"
"log"
"net/http"
"time"
) type logger struct {
Inner http.Handler
} func (l *logger) ServeHTTP(w http.ResponseWriter, r *http.Request) {
log.Printf("start %s\n", time.Now().String())
l.Inner.ServeHTTP(w,r)
log.Printf("finish %s",time.Now().String())
} func hello(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello\n")
} func main() {
f := http.HandlerFunc(hello)
l := logger{Inner: f}
http.ListenAndServe(":8000", &l)
}

Run the program and issue a request.

curl http://localhost:8000

最新文章

  1. GitHub的使用之新建与更新代码
  2. java 集合:实现
  3. LuaAlchemy API 介绍
  4. pushState()、popstate事件配合ajax实现浏览器前进后退页面局部刷新
  5. C&C++ recap
  6. .NET微信自定义分享标题、缩略图、超链接及描述的设置方法
  7. java 面向对象编程 第18章——网络编程
  8. 【linux】学习笔记
  9. 获取iOS设备属性
  10. centos主机建立ssh互信
  11. ios扫雷
  12. python_函数设计
  13. Hibernate Annotation _List/Map
  14. 改造一下jeecg中的部门树
  15. 关于vue中tamplate和DOM节点浅谈
  16. Android之密码的显示与隐藏
  17. HTTP 错误 404.0 - Not Found
  18. vcenter修改用户密码的方法
  19. Android 开发工具类 10_Toast 统一管理类
  20. 实现一个自定义event事件,包括on ,off,trigger,once

热门文章

  1. Docker中使用ElasticSearch
  2. jwt 工具类
  3. Java并发编程-深入Java同步器AQS原理与应用-线程锁必备知识点
  4. 【故障公告】阿里云 RDS 实例 CPU 100% 故障引发全站无法正常访问
  5. 程序员必备基础:Git 命令全方位学习
  6. html+css快速入门教程(3)
  7. 如何在Linux下使用Tomcat部署Web应用(图文)
  8. Nginx之upstream的四种配置方式
  9. 注解式HTTP请求Feign (F版)
  10. 利用binarySearch实现抽奖计算逻辑