vscode 插件安装
由于我个人使用的是vscode进行的操作,所以需要安装一下相应的插件,在插件安装好之后会自动提示安装依赖,国内源不大行,需要进行以下操作。
1 2
   | go env -w GO111MODULE=on go env -w GOPROXY=https://goproxy.cn
   | 
 
不一定即刻生效,如果失败可以考虑重启。
基础
go语言与其他语言一样,可以实现原生的web服务,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
   | package main
  import ( 	"fmt" 	"net/http" )
 
 
  func sayHello(w http.ResponseWriter, r *http.Request) { 	_, _ = fmt.Fprintln(w, "hello world!"); }
  func main() { 	http.HandleFunc("/hello", sayHello) 	err := http.ListenAndServe(":9090", nil) 	if err != nil { 		fmt.Println("http server failed, err:%v \n", err) 		return 	} }
   | 
 
直接Fs调试运行或者使用命令go run filename.go,如果没有报错就可以访问以下地址查看结果:
1
   | http://localhost:9090/hello
   | 
 
当然,如果这样返回的内容同样也可以是HTML标签信息,页面会自动渲染,如下:
1 2 3
   | func sayHello(w http.ResponseWriter, r *http.Request) { 	_, _ = fmt.Fprintln(w, "<h1 style='color:red'>hello Golang!<h1>"); }
  | 
 
接着可以更进一步,尝试返回一个html文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
   | package main
  import ( 	"fmt" 	"io/ioutil" 	"net/http" )
 
 
  func sayHello(w http.ResponseWriter, r *http.Request) { 	html, _ := ioutil.ReadFile("./template/hello.html") 	_, _ = fmt.Fprintln(w, string(html)); }
  func main() { 	http.HandleFunc("/hello", sayHello) 	err := http.ListenAndServe(":9090", nil) 	if err != nil { 		fmt.Println("http server failed, err:%v \n", err) 		return 	} }
   | 
 
以上操作需要在同目录下防止对应的文件才可以实现这个效果。
引入框架
通过上面的http包,就能够实现一个web的开发,但是框架的好处,就是别人帮我们搭建了一个舞台,同时提供了很多现成的轮子,让我们专注于业务的开发,同时让开发效率更高。
Gin是一个用Go语言编写的web框架。它是一个类似于martini但拥有更好性能的API框架, 由于使用了httprouter,速度提高了近40倍。 如果你是性能和高效的追求者, 你会爱上Gin。
Go世界里最流行的Web框架,Github上有32K+star。 基于httprouter开发的Web框架。 中文文档齐全,简单易用的轻量级框架。
安装
1
   | go get -u github.com/gin-gonic/gin
   | 
 
第一个案例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
   | package main
  import ( 	"github.com/gin-gonic/gin" )
  func main() { 	 	r := gin.Default() 	 	 	r.GET("/hello", func(c *gin.Context) { 		 		c.JSON(200, gin.H{ 			"message": "Hello world!", 		}) 	}) 	 	r.Run() }
   | 
 
基于以上案例可以尝试更改方法进行不同的测试操作,如POST、DELETE等
但是还是不够,可以更进一步,尝试实现一下HTML的渲染,如下:
1 2 3 4 5 6 7 8 9 10 11 12
   | func main() { 	r := gin.Default() 	r.LoadHTMLGlob("templates/**/*") 	
  	r.GET("users/index", func(c *gin.Context) { 		c.HTML(http.StatusOK, "users/index.html", gin.H{ 			"title": "users/index", 		}) 	}) 	r.Run(":8080") }
  | 
 
这里加载模板文件的时候有两种加载方式,依据情况使用
模板文件如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
   | {{define "users/index.html"}} <!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <meta name="viewport" content="width=device-width, initial-scale=1.0">     <meta http-equiv="X-UA-Compatible" content="ie=edge">     <title>users/index</title> </head> <body>     {{.title}} </body> </html> {{end}}
  | 
 
个人感觉用到模板文件的场景已经很少了,现在几乎都是前后端分离的状态,所以没有必要继续针对模板语句相关知识学习下去了。