go 语言实现一个简单的 web 服务器

学习Go语言的一些感受,不一定准确。

假如发生战争,JAVA一般都是充当航母战斗群的角色。
一旦出动,就是护卫舰、巡洋舰、航母舰载机、预警机、电子战飞机、潜艇等等
浩浩荡荡,杀将过去。
(JVM,数十个JAR包,Tomcat中间件,SSH框架,各种配置文件...天生就是重量级的,专为大规模作战)

而GO语言更像F35战斗轰炸机
单枪匹马,悄无声息,投下炸弹然后走人。
专属轰炸机,空战也会一点点.
实在搞不定,就叫它大哥F22。
(GO是编译型语言,不需要依赖,不需要虚拟机,可以调用C代码并且它足够简单,却非常全面)

计划Go语言学习的知识点
1.搭建Http服务
2.连接数据库
3.本地IO
4.多线程
5.网络
6.调用本地命令
7.调用C语言代码

首先,搭建一个静态的服务器
我写程序喜欢使用HTML通过AJAX发送JSON请求到后端处理。

HttpServer.go

  1. package main
  2. import (
  3.         "flag"
  4.         "io/ioutil"
  5.         "log"
  6.         "net/http"
  7.         "os"
  8.         "strings"
  9. )
  10. var realPath *string
  11. func staticResource(w http.ResponseWriter, r *http.Request) {
  12.         path := r.URL.Path
  13.         request_type := path[strings.LastIndex(path, "."):]
  14.         switch request_type {
  15.         case ".css":
  16.                 w.Header().Set("content-type", "text/css")
  17.         case ".js":
  18.                 w.Header().Set("content-type", "text/javascript")
  19.         default:
  20.         } 
  21.         fin, err := os.Open(*realPath + path)
  22.         defer fin.Close()
  23.         if err != nil {
  24.                 log.Fatal("static resource:", err)
  25.         } 
  26.         fd, _ := ioutil.ReadAll(fin)
  27.         w.Write(fd)
  28. }
  29. func main() {
  30.         realPath = flag.String("path", "", "static resource path")
  31.         flag.Parse()
  32.         http.HandleFunc("/", staticResource)
  33.         err := http.ListenAndServe(":8080", nil)
  34.         if err != nil {
  35.                 log.Fatal("ListenAndServe:", err)
  36.         } 
  37. }


网上看到一个更BT的方法..

  1. package main
  2. import (
  3.         "net/http"
  4. )
  5. func main() {
  6.         http.Handle("/", http.FileServer(http.Dir("/tmp/static/")))
  7.         http.ListenAndServe(":8080", nil)
  8. }


将EasyUI前端框架解压到 /tmp/static 目录下


在GOPATH下执行 
go run HttpServer.go --path=/tmp/static

查看网页,一切正常。


这样Go语言以不到50行代码,编译之后不到7M的可执行文件,就实现了一个简易的静态服务器。

原文地址:https://www.cnblogs.com/SofuBlue/p/8278871.html